class CarMaker extends React.Component {
constructor(props) { super(props); }
handleEvent() { /* common handler code */ }
getComponent() {
let component = null;
switch(type) {
case 'hatchback':
// unique logic about hatchbacks
// consider attribues computed inside each case
component = <HatchbackMaker {...hatchbackAttrs} />;
break;
case 'sedan':
component = <SedanMaker {...sedanAttrs} />;
break;
case 'truck':
component = <TruckMaker {...truckAttrs} />;
break;
}
// Is there any way to attach event handler like this dynamically?
component.onClick = this.handleEvent.bind(component);
return component;
}
render() {
let arr = [];
dataList.forEach(function(dataItem) {
arr.push(this.getComponent(dataItem.type));
}, this);
return (<div>{arr}</div>;)
}
}
什麼是添加的onClick處理程序的現有組件(在一個變量持有),並綁定該組件本身爲「本」價值的最佳方式是什麼?
不可以。您不應該動態添加事件,因爲您必須爲此使用'setState',但這是錯誤的做法。 這看起來像是你的代碼的體系結構問題,很難用這個有限的例子來解決,因爲你可能不應該使用switch語句來處理這樣的組件。發佈完整的代碼,以便我可以提供更多幫助。 dataList從哪裏來? –
你也有'handleClick'的代碼嗎? –
好吧,我明白你對架構的看法,目前雖然能夠動態地將onClick屬性添加到組件中,但會節省一些重複代碼。 –