Reputation: 15674
Given a component like this :
class App extends Component {
state = {}
sayHello() {
// 'this' is undefined here... It should point to the component instance
}
render() {
return (
<div onClick={this.sayHello}>
clickMe
</div>
);
}
}
how come sayHello can't access this
? That is not the expected behavior of an ES6 class.
What am I missing out on ?
Upvotes: 0
Views: 40
Reputation: 1518
In javascript this
depends on how you call the method. This can be changed by binding this
inside a method. To illustrate what is happening in your example:
class App {
sayHello() {
console.log(this)
}
}
const a = new App()
a.sayHello() // A {}
const callback = a.sayHello // what you are passing as a callback to onClick
callback() // undefined
To fix this problem you need to bind this
in sayHello
function. You can use class properties to achieve this. This is still an experimental feature of javascript but seems to be a community accepted way of binding this
for React components.
class App {
sayHello = () => {
console.log(this)
}
}
callback() // A {}
Upvotes: 2
Reputation: 4008
div
it self is another Class so when calls your sayHello
inside himself it will change this
.
All you have to do is bind this to sayHello or call it via ES6 arrow function.
<div onClick={ this.sayHello.bind(this) }>
or
<div onClick={ (event) => this.sayHello(event) }>
Upvotes: 0