Javascript 更改forEach循环中的状态
如何更改按钮上单击事件的状态?现在我有错误了 未捕获类型错误:this.setState不是函数 我知道我不能在这里使用this.setState,但我不知道我应该在哪里进行绑定Javascript 更改forEach循环中的状态,javascript,loops,reactjs,addeventlistener,setstate,Javascript,Loops,Reactjs,Addeventlistener,Setstate,如何更改按钮上单击事件的状态?现在我有错误了 未捕获类型错误:this.setState不是函数 我知道我不能在这里使用this.setState,但我不知道我应该在哪里进行绑定 class Popup extends React.Component { constructor(props){ super(props); this.state = {opened: false}; } componentDidMount(){ var popupOpenBtn
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
});
})
});
}
单击处理程序的作用域是按钮,而不是类。请尝试以下方法:
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
});
})
});
}
单击处理程序的作用域是按钮,而不是类。请尝试以下方法:
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
});
})
});
}
这是console.log(this)按钮,它永远不会直接改变this.state,因为以后调用setState()可能会取代您所做的改变。将此.state视为不可变的。是的,你是对的。但是我怎样才能弹出并更改它的状态呢?这是一个按钮,console.log(this)从不直接修改this.state,因为以后调用setState()可能会替换您所做的修改。将此.state视为不可变的。是的,你是对的。但我如何才能获得弹出窗口并更改其状态?在这种情况下,我有未捕获的TypeError:无法读取未定义的属性“setState”。所以这里不是我的组件在这种情况下我有未捕获的TypeError:无法读取未定义的属性“setState”。这不是我的组件