React Ref 和 React forwardRef - Go语言中文社区

React Ref 和 React forwardRef


  1. Ref 和Dom,Ref是reference(引用)的简写。

    1. 能力:大多数情况下,props前递可以解决一切问题,但是依然有需要触达React实例或者Dom节点的情况,这时候应该使用React Ref。
    2. 使用:
      1. 用来处理立即执行的动画。
      2. 用来处理非受控组件的焦点,什么是受控/非受控组件参考文章
      3. 用来与第三方库对接,我知道的有d3 或者 cocos。
  2. React.forwardRef((props,ref)=><Compnent>)

    1. 简而言之就是自动透传引用(Ref),能让组件接收传过来的ref, 向下(或者说向前)传递Ref。
      const FancyButton = React.forwardRef((props, ref) => (
        <button ref={ref} className="FancyButton">
          {props.children}
        </button>
      ));
      
      // You can now get a ref directly to the DOM button:
      const ref = React.createRef();
      <FancyButton ref={ref}>Click me!</FancyButton>;  
    2. 上述代码的解释:

      1. 首先创建了一个ref, 这个ref的目的就是抓到孙子组件中的input节点
      2. 通过组件属性把ref传给子组件<FancyButton>
      3. 子组件通过React.forwardRef透传props和ref,这里ref才是我们要注意的点。
      4. 参数ref赋值给孙子组件<button>
      5. 这个ref就能抓到孙子组件的实例。
  3. React.forwardRef((props, ref)=><Componnet>)在高阶组件中的使用:

    1. 比如我们写一个打印前后属性的高阶组件logProps,这个高阶组件能够透传ref
       1 function logProps(Component) {
       2   class LogProps extends React.Component {
       3     componentDidUpdate(prevProps) {
       4       console.log('old props:', prevProps);
       5       console.log('new props:', this.props);
       6     }
       7 
       8     render() {
       9       const {forwardedRef, ...rest} = this.props;
      11       // 把常规属性"forwardedRef"作为ref赋值给传过来的Component组件
      12       return <Component ref={forwardedRef} {...rest} />;
      13     }
      14   }
      15 
      16   // 注意React.forwardRef提供的第二个参数ref.
      17   // 我们可以把ref作为一个常规属性"forwardedRef"传给LogProps这个组件
      18   // 就可以跟实例绑定.
      19   return React.forwardRef((props, ref) => {
      20     return <LogProps {...props} forwardedRef={ref} />;
      21   });
      22 }

       

版权声明:本文来源博客园,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.cnblogs.com/dejunwang/p/11782484.html
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-11-17 12:39:58
  • 阅读 ( 1619 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢