/* child子组件 */
// https://reactjs.org/docs/hooks-reference.html#useimperativehandle
import {useState, useImperativeHandle} from 'react';
...
// props子组件中需要接受ref
const ChildComp = ({cRef}) => {
const [val, setVal] = useState();
// 此处注意useImperativeHandle方法的的第一个参数是目标元素的ref引用
useImperativeHandle(cRef, () => ({
// changeVal 就是暴露给父组件的方法
changeVal: (newVal) => {
setVal(newVal);
}
}));
...
return (
<div>{val}</div>
)
}
/* FComp 父组件 */
import {useRef} from 'react;
...
const FComp = () => {
const childRef = useRef();
const updateChildState = () => {
// changeVal就是子组件暴露给父组件的方法
childRef.current.changeVal(99);
}
...
return (
<>
{/* 此处注意需要将childRef通过props属性从父组件中传给自己 cRef={childRef} */}
<ChildComp cRef={childRef} />
<button onClick={updateChildState}>触发子组件方法</button>
</>
)
}
网友评论