I want to know the difference between these two statements in react.
If the function depends on having a calling context of the instance, and the function isn't bound to the current instance already, the first code won't work, because the this
inside callMe
will be undefined
:
class Component extends React.Component {
name = 'component_name';
Callme() {
console.log(this.name);
}
render() {
return (
<button onClick={this.Callme}>Click</button>
);
}
}
// Render it
ReactDOM.render(
<Component />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
The second code works, because the this
in the anonymous arrow function will inherit the this
from the outer scope, the instance:
class Component extends React.Component {
name = 'component_name';
Callme() {
console.log(this.name);
}
render() {
return (
<button onClick={() => this.Callme()}>Click</button>
);
}
}
// Render it
ReactDOM.render(
<Component />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
If the Callme
method does not need to refer to the instance, then either type of onClick
works.
Other solutions to this common problem include:
this.Callme = this.Callme.bind(this)
)onClick={this.Callme.bind(this)}>
)Defining the method as an arrow function in the constructor (or as a class field), rather than as a property of the prototype
class Component extends React.Component {
this.Callme = () => {
console.log(this.name);
}