简体   繁体   English

我使用.bind(this) 但在导入的 function 上一直未定义? Javascript 反应

[英]I use .bind(this) but it keeps been undefined on the imported function? Javascript React

I have a really big class with a lot of handlers, and the document it's starting to be illegible, I want to define the handlers methods outside my class and grouped on a document by type (all the tools have different handlers, so I catch the event and depending on the selectedTool I redirect it to the correct handler), then import those methods/functions and call them from another method like they were normal methods.我有一个非常大的 class 有很多处理程序,并且文档开始难以辨认,我想在 class 之外定义处理程序方法并按类型分组在文档上(所有工具都有不同的处理程序,所以我抓住了事件并根据 selectedTool 将其重定向到正确的处理程序),然后导入这些方法/函数并从另一个方法调用它们,就像它们是普通方法一样。

在此处输入图像描述

The first log, returns this correctly, but for some reason, the log from inside handleSelectorMouseDown returns "undefined" even tho i use.bind(this)第一个日志正确返回这个,但由于某种原因,handleSelectorMouseDown 内部的日志返回“未定义”,即使我使用.bind(this)

Try this:尝试这个:

handleSelectorMouseDown.bind(this)(e)

This will first bind the imported function to the correct scope, and then execute the function.这将首先将导入的function绑定到正确的scope,然后执行function。

Another option is to bind the function in the class constructor and use it later:另一种选择是在 class 构造函数中绑定 function 并稍后使用它:

class MyComponent {
    constrctor() {
      this.handleSelectorMouseDown = handleSelectorMouseDown.bind(this);
    }
}

Now you just need to call this.handleSelectorMouseDown(e)现在你只需要调用this.handleSelectorMouseDown(e)

You're using bind wrong, you have to first bind then call , I would create a reference at the class level for your binded handlers:您使用bind错误,您必须先bind然后call ,我会在 class 级别为您的绑定处理程序创建一个引用:

constructor() {
  this.onSelectorMouseDown = handleSelectorMouseDown.bind(this);
}

then you can call them as you like:然后你可以随意调用它们:

this.onSelectorMouseDown(e);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM