
我试图通过单击我通过 DOM 方法创建的按钮来更改状态。我尝试通过函数的参数将“this”作为变量传递
var self="this"
b.addEventListener("click", function(self){
self.setState({health:100}) })
Run Code Online (Sandbox Code Playgroud)
并尝试在函数末尾添加 .bind(this) 但没有运气。
b.addEventListener("click", function(){
this.setState({health:100}) })
Run Code Online (Sandbox Code Playgroud)
这个问题可以使用正确的声明和定义来处理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 });
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8217 次 |
| 最近记录: |