Javascript 将方法传递给子组件
我的React应用程序有几个类似的自定义按钮,可以执行不同的任务。UI在所有按钮中都是相似的,更改的是每个按钮必须触发的操作和标题 包含按钮的父组件的工作代码如下(类似):Javascript 将方法传递给子组件,javascript,reactjs,javascript-events,components,Javascript,Reactjs,Javascript Events,Components,我的React应用程序有几个类似的自定义按钮,可以执行不同的任务。UI在所有按钮中都是相似的,更改的是每个按钮必须触发的操作和标题 包含按钮的父组件的工作代码如下(类似): class Page extends Component { constructor(props) { super(props); } action1(){ //... do stuff... } action2(){ //... do
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>
);
}
}
类页扩展组件{
建造师(道具){
超级(道具);
}
行动1(){
//…做事。。。
}
行动2(){
//…做事。。。
}
render(){
返回(
{“button1”}
{“按钮2”}
);
}
}
是否可以将方法传递给子组件,传递方式与传递变量值的方式相同?我想把它变成这样:
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>
);
}
}
类页扩展组件{
建造师(道具){
超级(道具);
}
行动1(){
//…做事。。。
}
行动2(){
//…做事。。。
}
render(){
返回(
);
}
}
类CustomButton扩展组件{
建造师(道具){
超级(道具);
}
render(){
返回(
{this.props.title}
);
}
}
处理这种情况的正确方法和背后的理论是什么
我正在使用React with Meteor,以防它产生影响。您可以将道具传递给组件。传递的道具可以具有任何数据类型的javascript 在您的情况下,您希望传递一个动作道具,该动作道具具有一个函数作为值。然后访问组件中的动作道具并使用它
简言之,这背后没有任何理论依据。你所做的是正确的。这就是react处理向其他组件传递数据的方式。请注意,这不是将数据传递给子组件的唯一方法 是的,它就是这样工作的。你说的设计缺陷是什么?设计是按照OOP实现的。我刚刚测试了代码,它确实有效。这是一个幸运的巧合。我在Stackoverflow上写了这段代码,考虑到这将很好地证明我的意图,并且实际的解决方案将更加复杂。从来没有想过它会像现在这样工作!我猜这是为了展示React和JS的直观性。这可能是我在寻找推荐人之前需要测试的一个教训。无论如何,谢谢你的快速回答。这是正确的,代码正在工作。谢谢@FurkanO