React Hooks中父组件调用子组件方法
2022-08-01 本文已影响0人
X俊逍遥
子组件:
import {useState, useImperativeHandle,forwardRef} from 'react'
//props子组件需要接收 ref
const ChildComp = (props, ref) => {
const [val, setVal] = useState('')
// 此处注意useImperativeHandle方法的的第一个参数是目标元素的ref引用
useImperativeHandle(ref, () => ({
// changeVal 就是暴露给父组件的方法, newVal是父组件传递的参数
changeVal: (newVal) => {
setVal(newVal)
}
}))
return (
<div>{val}</div>
)
}
ChildComp = forwardRef(ChildComp)
export default ChildComp
父组件:
import {useRef} from 'react'
import ChildComp from './ChildComp.jsx'
const FComp = () => {
const childRef = useRef(null)
const updateChildState = () => {
// changeVal就是子组件暴露给父组件的方法
childRef.current.changeVal(99);
}
return (
<>
<ChildComp ref={childRef}></ChildComp>
<button onClick={updateChildState}>触发子组件方法</button>
</>
)
}
export default FComp