这是我的 React 类:
class Test extends React.Component {
constructor(props) {
super(props);
// bind functions
this._onClick = this._onClick.bind(this);
this._onMouseMove = this._onMouseMove.bind(this);
document.addEventListener("keydown", this._handleKeyDown);
this._handleClick = this._handleClick.bind(this);
}
_handleKeyDown(e) {
switch( e.keyCode ) {
// If the user presses the escape key
case 27:
this.exitFunction(document.getElementById('test_id'));
break;
default:
break;
}
}
_onClick(e) {
// do stuff
let cv = document.getElementById("test_id");
this.exitFunction(cv);
}
exitFunction(cv) {
console.log("in exit function");
}
}
当我从 _onClick
方法调用 this.exitFunction 时,没有收到任何错误。当我从 _handleKeyDown
调用它时,我收到一条错误消息:
Uncaught ReferenceError: exitFunction is not defined
at HTMLDocument._handleKeyDown
这是因为我为 _handleKeyDown
函数添加了监听器到文档中,但它无法使用 this.exitFunction
获取正确的上下文。
如果是这样,我如何使用正确的上下文调用 this.exitFunction()
?
编辑:
我在构造函数中添加了 _handleClick
的绑定(bind)。为什么我无法在 addEventListener
行之后添加绑定(bind)?我得到 this.exitFunction
is undefined,但如果我在 addEventListener
行之前添加它,它就可以正常工作。
最佳答案
您需要将 handleKeyDown
中的 this
关键字绑定(bind)到组件的执行上下文。否则,this
将在函数内未定义。
constructor(props) {
super(props);
// bind functions
this._onClick = this._onClick.bind(this);
this._onMouseMove = this._onMouseMove.bind(this);
this._handleKeyDown = this._handleKeyDown.bind(this);
document.addEventListener("keydown", this._handleKeyDown);
}
您还可以使用箭头功能以及 SiddAjmera 建议的功能。箭头函数具有词法绑定(bind),它们隐式接收组件的执行上下文。因此,您不需要它们将每个函数绑定(bind)到构造函数。
关于reactjs - 未捕获的类型错误 : exitFunction is not a function even though it is called successfully from another method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57264287/