子組件
import {useState, useImperativeHandle,forwardRef} from 'react';
// props子組件中需要接受ref
let ChildComp = (props,ref) => {
// 此處注意useImperativeHandle方法的的第一個參數(shù)是目標(biāo)元素的ref引用
useImperativeHandle(ref, () => ({
// changeVal 就是暴露給父組件的方法
changeVal: (newVal) => {
}
}));
return (
<div>{val}</div>
)
}
ChildComp = forwardRef(ChildComp)
父組件
/* FComp 父組件 */
import {useRef} from 'react';
const FComp = () => {
const childRef = useRef();
const updateChildState = () => {
// changeVal就是子組件暴露給父組件的方法
childRef.current.changeVal(99);
}
return (
<>
<ChildComp ref={childRef} />
<button onClick={updateChildState}>觸發(fā)子組件方法</button>
</>
)
}