当前位置: 移动技术网 > IT编程>开发语言>JavaScript > react修饰器对组件实例ref引用实例的影响

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

2020年03月16日  | 移动技术网IT编程  | 我要评论
ref: 获取组件实例的引用,即获取实例的this。 影响原因 当一个组件用了修饰器之后,其ref会被包裹一层,而不能找到真实的this实例。 ref在react组件中,同为关键字,子组件取不到该props 解决方法 在组件外层包裹一层 container,手动绑定ref 指定getInstance ...

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 官方文档

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网