高阶组件传值问题

记录:高阶组件从顶部获取下部的ref的问题

如果父组件和子组件之间直接相连,那么父组件通过ref可以直接获取到子组件的DOM;

<Child ref={(node) => {this.ref = node}}/>

如果中间有一个高阶组件,例如router或者翻译组件,设置子组件的ref,无法在父组件中访问 this.ref 获取子组件

解决方案:使用另一个props(例如 getInstance) 获取子组件的ref。ref 的实质就是子组件DOM。

// 父组件
<Child getInstance={ref => this.ref = ref}/>

// 子组件
if (this.props.getInstance) {
  this.props.getInstance = this;
}
// Just do one thing, pass `WrappedComponent` back to `getInstance` (if any)
class withRef extends Component {
  render() {
    // You directly modify this.props.ref in the react development mode will report an error, you are not allowed to modify
    const props = { ...this.props };
    // Assign getInstance to ref here
    // Pass to `WrappedComponent` so that getInstance can get the `WrappedComponent` instance
    if (typeof this.props.getInstance === 'function') {
      props.ref = this.props.getInstance;
    }
    return (<WrappedComponent {...props} />);
  }
};

Last update: September 12, 2022