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ハンドラを追加して、「この」の値とそのコンポーネント自体をバインドするための最良の方法は何でしょうか。考えてみての反応しますか
私はこれらが含まれているのか分からないので、あなたが渡すことができます属性とは別に、上記の例で小道具を示している割り当てgetComponent() {
let component = null;
switch(type) {
case 'hatchback':
// unique logic about hatchbacks
// consider attribues computed inside each case
component = <HatchbackMaker {...hatchbackAttrs} onClick={this.handleEvent.bind(this)}/>;
break;
case 'sedan':
component = <SedanMaker {...sedanAttrs} onClick={this.handleEvent.bind(this)}/>;
break;
case 'truck':
component = <TruckMaker {...truckAttrs} onClick={this.handleEvent.bind(this)}/>;
break;
}
return component;
}
時onClick
イベントを割り当てないのはなぜ
いいえイベントを動的に追加する必要はありません。このためにはsetStateを使用する必要がありますが、間違った方法です。 これはあなたのコードのアーキテクチャ上の問題のようで、このようなコンポーネントに対してswitch文を使用しないでください。私はもっと助けることができるように完全なコードを投稿してください。 dataListはどこから来たのですか? –
'handleClick'にはどのようなコードがありますか? –
私はあなたがアーキテクチャーについて何を言っているのか理解していますが、コンポーネントにonClick属性を動的に追加することができれば、繰り返しコードを節約できます。 'ホンダ・シティ'、 タイプ: 'セダン'、 shapeSVGURL: ''、 –