【发布时间】: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>
}
actions 与bindActionCreators 绑定到动作创建者
子组件只是从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) => { ... }而不是handleChildClick(source) { ... }。有了这个this将引用正确的对象,你不需要做that = this。只是一个旁注。 -
@LaFaulx,我知道那个教程,但是那里的代码不同 - 那里的类以不同的方式定义,我很困惑 :)
标签: reactjs components parent-child redux