无法在addEventListener函数中调用this.setState

时间:2018-04-02 04:59:33

标签: reactjs

enter image description here

我试图通过点击我通过DOM方法创建的按钮来更改状态。我尝试过#34;这个"通过函数的参数作为变量

var self="this"
b.addEventListener("click", function(self){
    self.setState({health:100}) })

并尝试在函数结束时添加.bind(this),但没有运气。

b.addEventListener("click", function(){
    this.setState({health:100}) })

4 个答案:

答案 0 :(得分:2)

您应该执行一个单独的功能来管理事件。然后将该函数绑定到构造函数。例如

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 (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }

另外,请记住:

  

使用React时,通常不需要调用addEventListener来在创建DOM元素后添加侦听器。相反,只需在最初呈现元素时提供一个侦听器。

Handling Events in react

答案 1 :(得分:1)

请在componentDidMount life cycyle中添加以上事件处理。

componentDidMount(){

 var self=this;
//add b defination here;

  b.addEventListener("click", function()=>{ 

   //remove self from callback.
   //self  here causing shadowing to above self defination used below

    self.setState({health:100}) });

    OR

    this.setState({health:100}) });

}

答案 2 :(得分:0)

使用:

var self=this

b.addEventListener(“click”,function(){     self.setState({health:100})})

从中删除双引号,它应该正常工作。

答案 3 :(得分:0)

不需要const self = this;(可选) 只需使用箭头功能即可。

b.addEventListener("click", () => {
    this.setState({ health: 100 });
  }