如何更改按钮上单击事件的状态?现在我有错误
未捕获类型错误:this.setState 不是函数
我知道我不能在这里使用this.setState,但我不明白我应该在哪里进行绑定(bind)
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
});
})
});
}
关于javascript - 更改 forEach 循环中的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38938047/