/* child子組件 */
// https://reactjs.org/docs/hooks-reference.html#useimperativehandle
import?{useState, useImperativeHandle} from?'react';
...
// props子組件中需要接受ref
const ChildComp = ({cRef}) => {
????const [val, setVal] = useState();
????// 此處注意useImperativeHandle方法的的第一個參數(shù)是目標(biāo)元素的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}>觸發(fā)子組件方法</button>
????????</>
????)
}