reactjs - 未捕获的类型错误 : exitFunction is not a function even though it is called successfully from another method

标签 reactjs

这是我的 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/

相关文章:

javascript - onChange 事件不会在 react 时被触发

reactjs - 如何使 TextInput 中的 selectionColor 属性透明?

reactjs - 在拖放过程中,如果任何组件悬停在当前组件上,当前组件会更改其样式。这没有按预期发生吗?

javascript - react-router 和 Next.js 有什么不同

javascript - ReactJS-访问不同页面上的数据

javascript - Reactjs:将 React 代码粘合到旧的 javascript 代码中

javascript - 比较对象字符串、字符串化恒等运算符和字符串

node.js - 配置.output.path : The provided value "./" is not an absolute path

javascript - 未捕获的范围错误 : `options.awareOfUnicodeTokens` must be set to `true` to use `YYYY` In date picker

javascript - 无法在 react 映射之外访问返回值