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])  
return <>
   <ChildCmp ref={childCmpRef}/>
   </>  
}

 

posted @ 2020-06-08 17:56  饭饭大人  阅读(2199)  评论(0编辑  收藏  举报