react hooks 之 useRef, useImperativeHandle
作者:互联网
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}/> </> }
标签:useRef,const,hooks,childCmpRef,value,react,return,ref,click 来源: https://www.cnblogs.com/lisiyang/p/13067287.html