【发布时间】:2019-11-05 06:40:02
【问题描述】:
我们都知道this 根据给定的 React 代码是未定义的。对于这个问题,我们有很多解决方案,比如绑定、箭头函数等。我想知道这种行为背后的原因。请解释this 引用的行为原因,而不是解决方案。
class Foo extends Component {
clickHandler() {
console.log(this);
}
render() {
return <button onClick = {this.clickHandler}> Click Me </button>;
}
}
【问题讨论】:
-
其实我认为
this一定是对创建按钮的引用。这就是它在纯 JavaScript 中的行为。但是在这里,在这段代码中,this出乎意料地是未定义的。我想了解它的原因。 -
接受者看这里freecodecamp.org/news/…
-
@MuhammadMuaaz 浏览这个medium.com/byte-sized-react/what-is-this-in-react-25c62c31480 你会得到更多的澄清
-
谢谢你,@Harish。此链接对使用
this有很大帮助。也感谢@Vahid Akhtar。
标签: javascript reactjs this