zoukankan      html  css  js  c++  java
  • React Ref 和 React forwardRef

    1. 用ref来触达dom元素或组件实例

      1. ref是reference(引用)的简写。
      2. 在数据流之外直接操作子孙组件:
        1. ref属性赋值给Html元素,那么this.ref.current就获取到html元素
        2. ref属性赋值给常规React组件,那么this.ref.current就获取到组件的实例
      3. 不要过度使用:
        1. 有需要直接触达和操作子孙组件实例或者操作子dom元素的情况,这时候应该使用React Ref。
        2. 如果属性下传能够解决问题,应该使用声明式的属性传递,而非命令式的ref。
      4. 使用场景:
        1. 用来处理立即执行的动画,(我们知道流畅的动画或对用户动作的即时响应一般需要脱离react数据流,需要直接操作DOM节点(D3.js)或者node节点(cocos.js))。
        2. 用来处理非受控组件(比如没有用onChange检测数值的input元素)的焦点,什么是受控/非受控组件参考文章
        3. 用来与第三方库对接,我知道的有d3 或者 cocos,因为第三方库需要获取dom或者节点。
    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:
        // 现在你可以获取DOM按钮的引用 const ref = React.createRef(); <FancyButton ref={ref}>Click me!</FancyButton>;  
      2. 上述代码的解释:

        1. 首先创建了一个ref, 这个ref的目的就是抓到子组件中的<button>DOM节点
        2. 通过组件jsx属性把ref传给子组件<FancyButton>,这一行
          <FancyButton ref={ref}>Click me!</FancyButton>; 
        3. FancyButton组件通过React.forwardRef透传props和ref,这里ref才是我们要注意的点。
        4. forwardRef参数是一个函数,这个函数有一个ref参数,将其赋给子组件<button> 的ref属性
        5. 当ref关联上之后,这个ref.current将指向<button>的DOM节点。
    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 }
    晚来一阵风兼雨
  • 相关阅读:
    android提供ToolBar实现划动菜单的陷阱
    style="display"之后不能获取offsetHeight或clientWidth这类测量的值
    onmouseenter与onmouseover
    使用Dom的Range对象处理chrome和IE文本光标位置
    js严格模式“use strict”
    正则表达式lastIndex属性浅析
    IE中的fireEvent和webkit中的dispatchEvent
    readonly=“readonly”与readonly=“true”
    【杂文】
    【洛谷p1015】【一本通p1309】回文数(noip1999)
  • 原文地址:https://www.cnblogs.com/dejunwang/p/11782484.html
Copyright © 2011-2022 走看看