2016-08-14 73 views
0

如何在按钮上单击事件时更改状态?现在我有错误在for循环中更改状态

遗漏的类型错误:this.setState不是一个函数

我知道,我不能在这里使用this.setState,但我不明白我应该在哪里做绑定

class Popup extends React.Component { 
    constructor(props){ 
    super(props); 
    this.state = {opened: false}; 
    } 

    componentDidMount(){ 
    var popupOpenBtn = document.querySelectorAll('[data-popup]'); 

    popupOpenBtn.forEach(function(item) { 
     item.addEventListener("click", function(){ 
     this.setState({ 
      opened: true 
     }); 
     }) 
    }); 
    } 
+0

这是按钮,执行console.log(本) – epascarello

+1

从来没有直接发生变异this.state,如调用的setState()之后可以代替你做的突变。将this.state视为不可变的。 – hakiko

+0

是的,你是对的。但是,我怎么能到Popup并改变它的状态? –

回答

2

您的点击处理程序的作用域是按钮,而不是类。试试这个:

class Popup extends React.Component { 
    constructor(props){ 
    super(props); 
    this.state = {opened: false}; 
    } 

    componentDidMount(){ 
    var popupOpenBtn = document.querySelectorAll('[data-popup]'); 
    var component = this; 

    popupOpenBtn.forEach(function(item) { 
     item.addEventListener("click", function() { 
     component.setState({ 
      opened: true 
     }); 
     }) 
    }); 
    } 
+0

在这种情况下,我有Uncaught TypeError:无法读取未定义的属性'setState'。所以这里*这*不是我的组件 –

+0

是的,它的工作原理!谢谢! –