在代码示例中无法理解其上下文

时间:2018-09-25 21:30:11

标签: javascript reactjs typescript

在下面的代码片段中,我不清楚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,当我单击按钮时,它说thisundefined,对我来说很清楚,React不是自动将this绑定到所有方法。

因此,一旦我直接从sayMyName内部调用{}方法,然后单击按钮,就会改变上下文。

添加屏幕截图

单击按钮之前 enter image description here

单击按钮后 enter image description here

2 个答案:

答案 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)

https://medium.freecodecamp.org/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb

此人针对您的问题写了一篇很好的文章。基本上,他是说您可以怪JavaScript的样子。

简而言之,this上下文不会丢失……它或多或少指向全局对象