useRef源码

useRef在网上看了好几篇博客+自己理解

let lastRef

function useRef(value){

  lastRef = lastRef || {current:value}

  return lastRef

}

我们利用这个useRef可以绑定dom,还可以自定义hook,这里我主要讲下自定义hook

usePre   比如有这个hooks是我写的,那么它可以替代componentWillReceiverProps

function usePre(){

  useEffect(() => {
      latestCount.current = count;
      console.log(latestCount.current)
    });  
  console.log(latestCount.current)

}

这里先揭开答案,下面的值是旧的,上面的值是新的,

因此我完全可以造出这样一个hooks

 继续补一下useRef代替dom使用时

我们自然用过React.createRef(),useRef也是一个样子只不过 {current:value}这样,

<Child ref={childRef} />,

当然我们在使用dom的时候也就自然要带上current.setText()方法这样使用

当我们父组件里面套用子组件,想在父组件中用到子组件的方法,我们可以借助 forwardRef(Child)   条件:Child是个函数组件,

 父组件里面用.current.setTextByParent()就可以了,

原文地址:https://www.cnblogs.com/MDGE/p/13849014.html