zoukankan      html  css  js  c++  java
  • [React] Forward a DOM reference to another Component using forwardRef in React 16.3

    The function forwardRef allows us to extract a ref and pass it to its descendants. This is a powerful tool, but should be used with caution to avoid unexpected ref behaviour. The technique of forwarding refs really starts to shine in combination with higher order components (HOCs).

    forwardRef should be used when you are using HOC and pasing the ref around from parent to child component.

    parent component:

    import React, { Component } from "react";
    import TextInput from "./TextInput";
    
    class App extends Component {
      inputRef = React.createRef();
    
      focusInput = () => {
        this.inputRef.current.focus();
      };
    
      render() {
        return (
          <React.Fragment>
            <TextInput inputRef={this.inputRef} />
            <button onClick={this.focusInput}>Focus</button>
          </React.Fragment>
        );
      }
    }
    
    export default App;

    child commponent:

    import React, { Component, Fragment } from "react";
    import logProps from "./logProps";
    
    class TextInput extends Component {
      render() {
        return <input ref={this.props.inputRef} />;
      }
    }
    
    export default logProps(TextInput);

    HOC componnet:

    import React, { Component } from "react";
    
    function logProps(Component) {
      class LogProps extends Component {
        componentDidUpdate(prevProps) {
          console.log("before update", prevProps);
          console.log("after update", this.props);
        }
    
        render() {
          const { forwardRef, ...rest } = this.props;
          return <Component {...rest} ref={forwardRef} />;
        }
      }
    
      const forwardRef = (props, ref) => {
        return <LogProps forwardRef={ref} {...props} />;
      };
    
      const name = Component.displayName || Component.name;
      forwardRef.displayName = `logProps(${name})`;
    
      return React.forwardRef(forwardRef);
    }
    
    export default logProps;

    Display name:

    Becasue HOC component doesn't have a correct display name in the dev tool, we need to set it up:

      const forwardRef = (props, ref) => {
        return <LogProps forwardRef={ref} {...props} />;
      };
    
      const name = Component.displayName || Component.name;
      forwardRef.displayName = `logProps(${name})`;
    
      return React.forwardRef(forwardRef);

  • 相关阅读:
    Run UliPad 4.1 Under Windows 7 64bit and wxPython 3.0.2
    Ubuntu下编译SuiteSparse-4.4.1和METIS-4.0.3
    Call Paralution Solver from Fortran
    Python调用C/Fortran混合的动态链接库-下篇
    调用gluNurbsCurve绘制圆弧
    glutBitmapCharacter及glBitmap在ATI显卡下无法正常显示的原因初探
    PyOpenGL利用文泉驿正黑字体显示中文字体
    图论常用算法之二 算法模板及建模总结
    图论常用算法之一 POJ图论题集【转载】
    通过身边小事解释机器学习是什么?
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9003540.html
Copyright © 2011-2022 走看看