gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:35:28 25 4
gpt4 key购买 nike

enter image description here

我正在尝试更改通过 DOM 方法创建的按钮的单击状态。我尝试通过函数的参数将“this”作为变量传递

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

还尝试在函数末尾添加 .bind(this) 但没有成功。

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

最佳答案

可以使用 self 的正确声明和定义来处理此问题。或者在 arrow function(implicit Lexical scope) 的帮助下

componentDidMount(){

//assuing b defined

//1. if you want to use self
const self = this; // this should not be double quoted;
b.addEventListener("click", function () {
self.setState({ health: 100 });
}

// 2. using arrow function ( implicit lexical scope)
b.addEventListener("click", ()=> {
this.setState({ health: 100 });
}
}

关于reactjs - 无法在 addEventListener 函数中调用 this.setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49605527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com