import {useState, useImperativeHandle} from 'react';
...
const ChildComp = ({cRef}) => {
const [val, setVal] = useState();
useImperativeHandle(cRef, () => ({
changeVal: (newVal) => {
setVal(newVal);
}
}));
...
return (
<div>{val}</div>
)
}
import {useRef} from 'react;
...
const FComp = () => {
const childRef = useRef();
const updateChildState = () => {
childRef.current.changeVal(99);
}
...
return (
<>
{}
<ChildComp ref={childRef} cRef={childRef} />
<button onClick={updateChildState}>触发子组件方法</button>
</>
)
}