【发布时间】:2016-11-22 00:49:28
【问题描述】:
我的 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 与 Meteor 一起使用,以防万一。
【问题讨论】:
-
是的,它就是这样工作的。你说的设计缺陷是什么?
-
该设计很好地实现了,因为它遵循 OOP。
-
我刚刚测试了代码,它确实有效。这是一个幸运的巧合。我在 Stackoverflow 上编写了代码,考虑到这将很好地证明我的意图,并且实际的解决方案会更复杂。从来没有想过它会按原样工作!猜猜它展示了 React 和 JS 的直观性。在寻找参考之前,这可能是对自己进行测试的一个教训。无论如何,感谢您的快速回答。
标签: javascript reactjs components dom-events