我写了两个示例组件来展示我正在尝试做什么。 如果电话来自同一个类(class),我可以像下面那样做。
onClick={this.myFunc.bind(this, param1, param2)}
我如何从无状态组件做同样的事情,而不需要搞乱绑定(bind)“this”。
onClick={props.onClick['need to add params']}
import React from 'react';
class BigComponent extends React.Component{
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(param1, param2){
// do something with parameters
}
render(){
return(
<div>
<SmallComponent handleClick={this.handleClick}/>
</div>
);
}
}
function SmallComponent(props){
return(
<div>
<button onClick={ () => {props.handleClick('value_1', 'value_2')}}></button>
<button onClick={ () => {props.handleClick('value_3', 'value_4')}}></button>
{/* how to do above without arrow functions, because I read that it's not optimized*/}
</div>
);
}
最佳答案
在 this.myFunc
中添加回调。
this.myFunc = event => (param1, param2) => { ... do stuff }
在您的顶级组件中,您可以:
handleClick={this.myFunc}
在您的 child 中,只需:
onClick={handleClick(param1, param2)}
希望对您有所帮助。
或者,您可以执行以下操作:
function SmallComponent(props){
const handleClick = (param1, param2) => (event) => props.handleClick(param1, param2);
return(
<div>
<button onClick={handleClick(param1, param2)}></button>
...
);
}
关于javascript - 将参数传递给 React 中的 props 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49335869/