I've created a simple example for you.
class Example extends React.Component {
constructor(){
this.state = {
item : 'hello World'
}
/* this.click = this.click.bind(this) */
}
click(){
console.log(this)
console.log(this.state.item)
}
render(){
return <div>
<button onClick={this.click}>Click Me</button>
</div>
}
}
React.render(<Example />, document.getElementById('container'));
So if you click on a button you will get next in console
:
console.log(this) // undefined
console.log(this.state.item) // Type Error, Cannot read property 'state' of undefined
That's occurs because inside click
method this
links to the undefined
, but we want to display our states
.
How can you fix it? To make sure that we get correct context inside click
method we bind(this)
it. remove comments from this line /* this.click = this.click.bind(this) */
and you will get correct behavior of your method.
Worked example fiddle
I hope it will help you.
Thanks.