I know that similar topics are discussed in the field of review.
Using the following component
import React from 'react';
import ReactDOM from 'react-dom';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
}
addMore() {
this.setState({
counter: this.state.counter + 1
});
}
render() {
return (
<div onClick={ this.addMore }>
<p>counter: { this.state.counter }</p>
</div>
);
}
}
if (document.getElementById('example')) {
ReactDOM.render(<Example />, document.getElementById('example'));
}
When you click div, you getCannot read property 'setState' of null
I know that you can do things like this.addMore.bind(this), but it all seems like a weird extra pattern-style code to make it work.
What is considered the most elegant way to do this? Do people really have to have a preferred method that has their own benefits, other than being a sore eye?
source
share