My Reactアプリには、さまざまなタスクを実行するいくつかの同様のカスタムボタンがあります。 UIはすべてのボタンで似ていますが、それぞれのトリガーが必要とするアクションとタイトルが変更されています。子へのメソッドの受け渡し
ボタンを含む親コンポーネントのための作業コードは、次の(類似)である:
class Page extends Component {
constructor(props) {
super(props);
}
action1(){
//... do stuff...
}
action2(){
//... do stuff...
}
render(){
return(
<div className="table-row">
<div className="table-cell">
<div className="button"
onClick={this.action1.bind(this)}>{"button1"}
</div>
</div>
<div className="table-cell">
<div className="button"
onClick={this.action2.bind(this)}>{"button2"}
</div>
</div>
</div>
);
}
}
子コンポーネントには、変数値に対して行われるのと同じ方法を方法を渡すことは可能です?私はこれを次のように変えたい:
class Page extends Component {
constructor(props) {
super(props);
}
action1(){
//... do stuff...
}
action2(){
//... do stuff...
}
render(){
return(
<div className="table-row">
<div className="table-cell">
<CustomButton action={this.action1.bind(this)} title={"button1"}/>
</div>
<div className="table-cell">
<CustomButton action={this.action2.bind(this)} title={"button2"}/>
</div>
</div>
);
}
}
class CustomButton extends Component{
constructor(props){
super(props);
}
render() {
return (
<div className="table-cell"><div className="button"
onClick= {this.props.action}>{this.props.title}
</div>
);
}
}
この状況とその背後にある理論を正しく扱うにはどうすればよいでしょうか?
違いがある場合は、React with Meteorを使用しています。
はい、そのように正確に動作します。あなたはデザインの欠陥は何ですか? – azium
デザインはOOPに従うので、うまく実装されます。 –
私はちょうどコードをテストし、それは動作します。これは幸運な偶然でした。私はそれが私の意図の良いデモであり、実際の解決策はもっと複雑になると考えて、Stackoverflowにコードをここに書いた。実際にはそれが実際にはうまくいくとは思わない!それは、直感的なReactとJSがどれだけのことができるかを示すことになると思います。おそらく参考になる前に自分自身にレッスンをしてテストしてもいいでしょう。とにかく、素早く答えてくれてありがとう。 –