【问题标题】:How to use refs with react-redux's connect HOC on two components?如何使用 refs 和 react-redux 在两个组件上连接 HOC?
【发布时间】:2018-09-27 19:35:07
【问题描述】:

我有两个组件都使用连接 HOC。

import {connect} from "react-redux";
import ComponentB from "./ComponentB";
 
class ComponentA extends Component {
  render(){
    return {
        <div>
      <button
       onClick={this.refs.ComponentB.showAlert()}
      >
       Button
      </button>

      <ComponentB
       ref={instance => {
          this.ComponentB = instance.getWrappedInstance();
       }}
      />

    </div>
    }
  }
}

export default connect(mapStateToProps, {}, null, {withRef: true})(ComponentA)

将 ComponantA 与 connect HOC 结合使用会给我错误“TypeError: Cannot read property 'getWrappedInstance' of null”

   export default ComponantA;

不使用 HOC 不会给我这个错误。

import {connect} from "react-redux";
class ComponentB extends Component {
 showAlert = () => {
    alert("Please Work");
  }
 
render(){
 return {
     <div>ComponentB</div>
    }
  }
}
 
export default connect(mapStateToProps, {}, null, {withRef: true})(ComponentB)

【问题讨论】:

  • 我编辑了,谢谢。这不会是一个错字。这将是关于 refs 的问题,我不知道如何解决。
  • 取决于您使用的反应版本,如果 16 + 您可能需要使用 createRef - 请参阅文档reactjs.org/docs/refs-and-the-dom.html#dont-overuse-refs
  • 是的,我使用的是 16+。谢谢,我会看看文档。

标签: reactjs redux react-redux


【解决方案1】:

React.createRef 是在 React 16.3 中引入的,应该像这样使用:

this.componentBRef = React.createRef();
...

  <button
   onClick={() => this.componentBRef.current.getWrappedInstance().showAlert()}
  >
   Button
  </button>

  <ComponentB
   ref={this.componentBRef};
   }}
  />

正如this answer 中所述,createRef 中使用的模式允许通过current 属性延迟访问引用,因为this.componentBRef.current 最初是null。

由于使用了 Redux,因此组件之间的交互可能应该通过 Redux 来执行。

【讨论】:

猜你喜欢
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
  • 2019-05-01
  • 2020-11-01
  • 2018-10-21
  • 1970-01-01
  • 2020-04-30
相关资源
最近更新 更多