简体   繁体   中英

React Native: if you use arrow functions, is there ever a need to use bind(this)?

I know that in ES6, arrow functions have the property of not having their own this . Does this mean that there's no longer any scenario where you'd need to .bind(this) on any function in React Native? If not, can you give me a scenario where you would still need to use .bind(this) ?

Simple answer, NO, if you use ES6 syntax to declare class methods, then this in them will be automatically bound to the current class instance:

class MyComponent extends React.Component {
  myMethod1 = () => {
    ...
  }
  myMethod2 = () => {
    ...
  }
}

Thats why and how javascript works with this keyword. So you dont need to. And to mention that it all depends on you, suppose you declare a method in non ES6 way, then you have to bind it.

Hope it helps. feel free for doubts

There's no need and it would also not accomplish anything. Arrow functions cannot have their this changed so the first argument to .bind() is completely ignored.

.bind() can still be useful for binding arguments to the function invocation though, for instance: setTimeout(myFunction.bind(null, myVariable), 100) . Of course, that's essentially the same thing as writing setTimeout(() => myFunction(myVariable), 100)

It's still better to use them, you can even use modules that do the job for you (react autobind).

Because let's say you pass a method ( callback() as a prob) from a parent component to a child component....

when you call that method from inside the child component with or without the arrows you get errors (not this is not defined but it the wrong one and might not find some properties such as this.state.oncallback in the parent component which will be the main purpose of callback() ) since the lexical environment would be the one of the child component.

So binding it first to the parent is the right thing to do almost always:)

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