在React中调用父组件中从子组件定义的事件处理程序

时间:2016-03-03 22:21:52

标签: reactjs components parent-child redux

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

我对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>
  }
}

虽然这有效,但我不想在this中保留对that的引用,并且在bind中调用that.handleChildClick.bind(that, source)函数是正确的还原/反应方式

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

一个好方法是在构造函数中定义handleChildClick,这是为了防止每次通过onClick调用函数时重新创建函数。要解决this => 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>
  }
}
相关问题