简体   繁体   中英

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.

在此处输入图像描述

The first log, returns this correctly, but for some reason, the log from inside handleSelectorMouseDown returns "undefined" even tho i use.bind(this)

Try this:

handleSelectorMouseDown.bind(this)(e)

This will first bind the imported function to the correct scope, and then execute the function.

Another option is to bind the function in the class constructor and use it later:

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

Now you just need to call 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:

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

then you can call them as you like:

this.onSelectorMouseDown(e);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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