我正在学习React,我遇到了事件处理程序。在React中,建议先将函数绑定到this,然后再将其用作事件处理程序。然而,我没有绑定它,我仍然得到了想要的输出。下面是我的代码:
import React, { Component } from 'react';
class Experiment extends Component {
constructor(props){
super(props);
}
clickEvent(e){
e.preventDefault();
document.getElementById('change').innerHTML="This text changed";
}
render(){
return(
<div>
<p id='change'>This paragraph will change</p>
<button onClick={this.clickEvent}>Press me</button>
</div>
);
}
}
export default Experiment;正如您所看到的,我还没有将clickEvent()绑定到this,但是onClick事件可以顺利地工作。为什么会这样呢?我假设我会得到一个undefined错误或其他错误
https://stackoverflow.com/questions/50616137
复制相似问题