1 用法如下: // 子组件 const ChildCmp =(props, ref) => { const [value, setValue] = useState(''); const click = useCallback(() => { console.log(value) }, [value]) // 将click方法暴露出去。父组件可以通过ref获取到 useImperativeHandle(ref, () => { return {clickfun: click} }) return <>123</> }
// 父组件 const ParentCmp =(props) => { const [value, setValue] = useState(''); const childCmpRef= useRef(null); const click = useCallback(() => { childCmpRef&&childCmpRef.current&&childCmpRef.current.clickfun&&childCmpRef.current.clickfun() }, [value]) // 将click方法暴露出去。父组件可以通过ref获取到 useImperativeHandle(ref, () => { return {clickfun: click} }) return <> <ChildCmp ref={childCmpRef}/> </> }