react修饰器对组件实例ref引用实例的影响

ref: 获取组件实例的引用,即获取实例的this。

影响原因

  • 当一个组件用了修饰器之后,其ref会被包裹一层,而不能找到真实的this实例。
  • ref在react组件中,同为关键字,子组件取不到该props

解决方法

  • 在组件外层包裹一层 container,手动绑定ref 指定getInstance方法为获取其ref方法
function withRef(Wrap) {
  return class extends Component {
    constructor(props) {
      super(props);
    }

    getRefs = o => {
      const { getInstance } = this.props;
      if (getInstance) {
        getInstance(o)
      }
    }

    test2 = () => 222

    render() {
      return <Wrap {...this.props} ref={this.getRefs} />
    }
  }
}
  • 针对 react-redux 的 connect 高阶组件
    • v6.0 版本以下可用上述第一个方法对其包裹
    • v6.0 以上(包括6.0)可添加 forwardRef 参数˛-w845

react-redux 官方文档 https://react-redux.js.org/api/connect

原文地址:https://www.cnblogs.com/shenggao/p/12496057.html