3
在父級中調用在父級中定義的事件處理函數在我的redux/react應用程序中,我有一個父組件SourceList
,其中包含類型爲SourceItem
的子項。我決定(並不確定是否對react/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
中,並調用bind
函數,如that.handleChildClick.bind(that, source)
是正確的還原/反應方式。
感謝您的幫助!
終極版教程給出了完全一樣的情況的例子 - http://redux.js.org/docs/basics/UsageWithReact.html –
只是想補充一點,你可以爲函數使用ES6語法並執行'handleChildClick =(source)=> {...}'而不是'handleChildClick(source){...}'。有了這個'this'將引用正確的對象,你不需要做'that = this'。只是一個側面說明。 – Chris
@LaFaulx,我知道那個教程,但代碼有不同 - 那裏的類以不同的方式定義,我很困惑:) –