I have this here component. I want to pass down a call handler to each listElement I create. If I do it like below, with bind(this)
, it works properly. The problem is that I get this warning from React in the console: bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call.
var MyList = React.createClass({
render: function () {
var listElements = this.props.myListValues.map(function (val) {
return (
<ListElement onCallHandler={this.props.parentsCallHandler} val={val} />
);
}.bind(this));
return (
<ul>
{listElements}
</ul>
);
}
});
If I don't bind it, my children don't know about the call handler. What could I have done differently?
PS:
I know about destructuring assignments, like explained http://facebook.github.io/react/docs/transferring-props.html#transferring-with-...-in-jsx, but I don't want to use Harmony.
Binding methods helps ensure that the second snippet works the same way as the first one. With React, typically you only need to bind the methods you pass to other components. For example, <button onClick={this.handleClick}> passes this.handleClick so you want to bind it.
To avoid the need for binding we have something introduced in ES6 as arrow functions. Using the arrow function to call this. setState will lead to avoid the use of bind.
ReactJS bind() Method The bind() is an inbuilt method in React that is used to pass the data as an argument to the function of a class based component.
Bounded function in JavaScript is a function that is bounded to a given context. That means no matter how you call it, the context of the call will stay the same.
The error is coming from somewhere else in the code. You get the error when you do this.someFunction.bind(something)
and something isn't null
.
this.someFunction.bind({}, foo); // warning
this.someFunction.bind(this, foo); // warning, you're doing this
this.someFunction.bind(null, foo); // okay!
Do a search for .bind(this
in your code to find the offending line.
Here is updated docs example
React.createClass({
onClick: function(event) {/* do something with this */},
render: function() {
return <button onClick={this.onClick} />;
}
});
Update in ReactJS Docs
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