Uncaught TypeError: Cannot read property ‘props‘ of undefined

报错:Uncaught TypeError: Cannot read property 'props' of undefined

代码:在react-class组件中写了个方法,对应监听事件,如下:

onKeyUp(e: any) {
        if (e.keyCode !== 13) {
            return;
        }
        this.props.addItem(e.target.value);
}

原因:this指向的问题。应该要改为箭头函数(arrow function)。

使用常规函数定义,函数this指向由调用时决定,fun1被obj调用,函数this指向obj。


箭头函数的this不是在调用的时候决定的,而是在定义的时候决定的
2.箭头函数的this指向首先看其外部有没有函数,
1)如果有,它的this指向和这个外部函数绑定,当外部函数被调用时, this指向哪里,箭头函数则指向哪里。
2)如果没有外部函数,则箭头函数的this指向Window


箭头函数被调用时的this指向不能够通过call,apply,bind进行绑定,
由于箭头函数的this在定义的时候就决定了,所以不能在其被调用时进行改变

猜你喜欢

转载自blog.csdn.net/kaiyuantao/article/details/115477456
今日推荐