我的 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,以防它有所作为。
最佳答案
您可以将 props 传递给组件。传递的 Prop 可以有任何数据类型的 javascript。
在你的例子中,你想传递一个 Action Prop ,它有一个函数作为值。然后你在你的组件中访问 Action Prop 并使用它。
简而言之,它背后没有任何理论。你在做什么是正确的。这就是 React 处理将数据传递给其他组件的方式。请注意,这不是将数据传递给子组件的唯一方法。
关于javascript - 将方法传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40732053/