在下面的代码片段中,我不清楚React是如何管理 的。
class Main extends React.Component {
private name: string
constructor(props: any) {
super(props)
this.name = 'heisenberg'
}
render() {
return (
<div>
{this.sayMyName()}
<button onClick={this.sayMyName}>Say My Name</button>
</div>
)
}
sayMyName(): string {
return this.name
}
}
这是第一次在页面上打印heisenberg
,当我单击按钮时,它说this
是undefined
,对我来说很清楚,React
不是自动将this
绑定到所有方法。
因此,一旦我直接从sayMyName
内部调用{}
方法,然后单击按钮,就会改变上下文。
添加屏幕截图
答案 0 :(得分:6)
onclick事件是异步的。调用回调时,它是从全局上下文中调用的,因此this
在非严格模式下设置为window
对象,在严格模式下未定义。
要解决此问题,请在render方法中创建一个箭头函数(箭头函数从其定义的上下文中获取this
的值),然后将其传递给按钮:
<button onClick={event => this.sayMyName(event)}>Say My Name</button>
或创建sayMyName的绑定版本
constructor(props: any) {
super(props);
this.name = 'heisenberg';
this.sayMyName = this.sayMyName.bind(this);
}
答案 1 :(得分:2)
此人针对您的问题写了一篇很好的文章。基本上,他是说您可以怪JavaScript的样子。
简而言之,this
上下文不会丢失……它或多或少指向全局对象