I have a question about passing arguments to React click handlers. I have the following code, but for some reason the node argument is not passed to the toggle function. Shouldn't it? It's defined this way because it's a recursive component.
var Element = React.createClass({
toggle: function(e,node){
},
render: function(){
var nodes = this.props.children.map(function(n){
return <Element node={n} text={n.text} children={n.children} />
});
return (
<span onClick={this.toggle.bind(this,this.props.node)}>{this.props.text}</span>
);
}
});
Passing the event object of react as the second argument. If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.
We set the onClick prop on the button element. Every time the button is clicked, the handleClick function is invoked. To get the value of the input field on button click, we simply access the message state variable in our handleClick function.
When you add an onClick prop to the LinkButton component, it is just a property of an object. By calling props. onClick from inside of that component you are just calling a function that is stored inside of a property, similar to this: let props = { onClick: function () { alert("Executed!"); } }; props.
Function.prototype.bind
bind arguments beginning from left. The correct way to receive the node argument is to look for it at the very left position of the argument list:
toggle: function(node, event) {
console.log('node', node);
console.log('event', event);
}
See http://jsfiddle.net/8xxfgce7/ for an example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With