Saturday, 1 October 2016

reactjs - Cannot call this.setState in addEventListener function

You should do a separate function that manages the event. And then bind the function to the constructor. For example



class Toggle extends React.Component {

constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));

}
render() {
return (

);
}



Also, take in count this :




When using React you should generally not need to call addEventListener to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered.




Handling Events in react

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...