Reputation: 149
I wrote two sample components to show what I'm trying to do. If the call was from the same class, I could do like below.
onClick={this.myFunc.bind(this, param1, param2)}
How do I do the same thing from a stateless component without the need to mess with binding '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>
);
}
Upvotes: 3
Views: 13502
Reputation: 337
Add a callback inside of this.myFunc
.
this.myFunc = event => (param1, param2) => { ... do stuff }
In your top level component you can do:
handleClick={this.myFunc}
In your child, just do:
onClick={handleClick(param1, param2)}
Hope this is helps.
Alternatively you can do the following:
function SmallComponent(props){
const handleClick = (param1, param2) => (event) => props.handleClick(param1, param2);
return(
<div>
<button onClick={handleClick(param1, param2)}></button>
...
);
}
Upvotes: 4