I'm trying to get to work this code.
/*
* A simple React component
*/
class Application extends React.Component {
num = 42;
render() {
return (
<button onClick={this.show}>show</button>
);
}
componentDidMount() {
console.log(this.num);
}
show() {
console.log(this.num);
}
}
/*
* Render the above component into the div#app
*/
React.render(<Application />, document.getElementById('app'));
The problem is, when I click the button to get the property's value, it will be undefined. The interesting part is that the ComponentDidMount()
function can access the num
value.
I think that the show()
function has different context, and that's why I can't refer to num
via this
keyword. I tried to bind the num
value in the constructor, but it didn't work either, so I removed it.
Any idea how can I get the num
value by clicking on the button?