子组件
import React, { useImperativeHandle, forwardRef } from "react"
let Child = (props, ref) => {
useImperativeHandle(ref, () => ({
getInfo,
refreshInfo: () => {
console.log("子组件refreshInfo方法")
}
}))
const getInfo = () => {
console.log("子组件getInfo方法")
}
return (
<View>子组件</View>
)
}
Child = forwardRef(Child)
export default Child
父组件
import React, { Component } from 'react'
import Child form './Child'
export default class Parent extends Component {
super(props)
this.state = {
childRef: {}
}
getChildCallback = () => {
const {childRef} = this.state
childRef.getInfo && childRef.getInfo()
childRef.refreshInfo && childRef.refreshInfo()
}
childRefFunc= (ref) =>{
this.setState = ({childRef: ref || this.state.childRef})
}
return (
<View>
<View onClick={this.getChildCallback.bind(this)}>触发子组件方法</View>
<Child ref={this.childRefFunc} />
</View>
)
}
|