Reputation: 8946
I am new to React and js I need some clarifications on binding of methods in components
I have 2 components ParentComponent and ChildComponent
Parent
var ParentComponent = React.createClass({
methodArg: function (value) {
console.log("methodArg called", value);
},
methodNoArg: function () {
console.log("methodNoArg called");
},
render: function () {
return <ChildComponent m1={(value) => this.methodArg(value)} m2={() => this.methodNoArg} />
}
})
Child
var ChildComponent = React.createClass({
render: function () {
return (
<div>
<button onClick={()=>this.props.m1(100)}>Call M1</button>
<button onClick={()=>this.props.m2()}>Call M2</button>
</div>
)
}
})
When i click Call M1 button, methodArg() of parent is getting called.
But when I click Call M2 methodNoArg() is not getting called. What is the issue in this ?
When I pass methodNoArg to Child , it is getting called
<ChildComponent m1={this.methodArg()} m2={this.methodNoArg} />
But methodArg() is getting called without clicking the button , its getting called everytime when the child component is rendered.
Upvotes: 2
Views: 1633
Reputation: 531
<button onClick={()=>this.props.m1(100)}>Call M1</button>
Your above line is saying evaluate the m1 method and assign the result to onClick. So when you refresh your page you console.log statement with value you passed gets printed but it will never gets called again no matter how many times you click the button as onClick now does not have method assigned to it now.
You can achieve what you want by removing that parenthesis which is calling the method automatically without clicking.
Here is working jsfiddle code link : http://jsfiddle.net/fp0LvkLg/
Upvotes: 2
Reputation: 62405
This is because of the way you assign your method to a prop
m2={() => this.methodNoArg}
is (kind of if we omit the intricacies of this
) equivalent to
m2={function() {return this.methodNoArg}}
So your prop is a function, which returns a function, which in turn is never called.
You want to simply assign your function to a prop like this:
m2={this.methodNoArg}
Upvotes: 1