【问题标题】:Calling an event handler defined in parent from child component in React从 React 中的子组件调用父组件中定义的事件处理程序
【发布时间】:2016-06-17 11:47:12
【问题描述】:

在我的 redux/react 应用程序中,我有一个父组件 SourceList,其中包含 SourceItem 类型的子项。我决定(不确定 react/redux 是否真的如此)让子控件忽略单击处理程序是什么,并将单击事件处理程序从父级传递给子级。

我对 redux/react 还是很陌生,代码如下

componentDidMount() {
  const { actions } = this.props;
  if(this.props.side === 'right') { return; }
  actions.fetchSources(); // this works perfectly
}

handleChildClick(source) {
  const { actions } = this.props;
  if(this.props.side === 'right') { 
    actions.changeRight(source); 
    return; 
  }
  actions.changeLeft(source);
}

render() {
  const { actions } = this.props.actions;
  var that = this;
  var rightSide = this.props.side === 'right';
  var sources = this.props.sources.items.map(function(source) {
    return <SourceItem 
              key={source.id} 
              onClick={that.handleChildClick.bind(that, source)}
              source={source}/>;
    });
  return <ul>{sources}</ul>
}

actionsbindActionCreators 绑定到动作创建者

子组件只是从props获取值:

class SourceItem extends React.Component {
  render() {
    const { onClick, selected, source } = this.props;
    return <li onClick={onClick}>{source.name}</li>
  }
}

虽然这可行,但我不想在 that 中保留对 this 的引用并像在 that.handleChildClick.bind(that, source) 中那样调用 bind 函数是正确的 redux/react 方式。

感谢您的帮助!

【问题讨论】:

  • Redux 教程给出了完全相同的例子——redux.js.org/docs/basics/UsageWithReact.html
  • 只是想补充一点,您可以对函数使用 ES6 语法并使用 handleChildClick = (source) =&gt; { ... } 而不是 handleChildClick(source) { ... }。有了这个this 将引用正确的对象,你不需要做that = this。只是一个旁注。
  • @LaFaulx,我知道那个教程,但是那里的代码不同 - 那里的类以不同的方式定义,我很困惑 :)

标签: reactjs components parent-child redux


【解决方案1】:

一个好的方法是在构造函数中定义handleChildClick,这是为了防止函数在每次通过onClick 调用时都被重新创建。要同时解决this =&gt; that 的问题,请使用箭头功能。

constructor([props]) {
  this.handleChildClick = this.handleChildClick.bind(this)
} 

....
render() {
  const { actions } = this.props.actions;
  var rightSide = this.props.side === 'right';
  var sources = this.props.sources.items.map((source) => {
    return <SourceItem 
          key={source.id} 
          onClick={this.handleChildClick}
          source={source}/>;
    });
  return <ul>{sources}</ul>

}

.....

class SourceItem extends React.Component {
  render() {
    const { onClick, selected, source } = this.props;
    return <li onClick={onClick(source)}>{source.name}</li>
  }
}

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 2017-06-14
    • 2020-01-05
    • 1970-01-01
    • 2016-10-19
    • 2017-01-08
    • 2014-01-27
    • 1970-01-01
    • 2016-03-07
    相关资源
    最近更新 更多