【问题标题】:Access ref of a redux connected component访问 redux 连接组件的 ref
【发布时间】:2018-01-03 22:41:18
【问题描述】:

我曾经有一个这样的组件:

class BlahDumb extends Component {
   toggleMe = () => console.log('toggling')
   render() {
      ...
   }
}

然后我会这样使用它:

class App extends Component {
    doIt = () => this.el.toggleMe()
    refEl = el => this.el = el;
    render() {
       return (
          <div>
              <BlahDumb ref={this.refEl} />
              <button onClick={this.doIt} />
          </div>
       )
    }
}

现在效果很好,直到我将 Blah 连接到 redux。

我把 Blah 改成了这样:

const Blah = connect(function() { ... })(BlahDumb);

现在我无法再从通过 ref 获得的 this.el 访问 toggleMe。这是不好的模式吗?或者有没有办法获得孩子的参考?

【问题讨论】:

  • 怀疑是您可能没有正确导出组件。试试export default connect(function() {})(BlahDumb)

标签: react-redux


【解决方案1】:

连接你的子组件传递选项参数来连接喜欢

const Blah = connect(
    mapStateToProps,
    mapDispatchToProps,
    null,
    { withRef: true }
)(BlahDumb)

并在您的父组件中使用 getWrappedInstance() 函数调用子组件中的方法。

this.el.getWrappedInstance().toggleMe()

【讨论】:

    猜你喜欢
    • 2019-12-03
    • 2023-03-30
    • 2020-02-26
    • 2019-05-18
    • 1970-01-01
    • 2020-11-01
    • 2018-11-18
    • 1970-01-01
    • 2020-04-28
    相关资源
    最近更新 更多