In react native navigator component. I move renderScene attr out to a class method. It check if route.id match and return component. It forces me to use "this" but i don't think i need it. I am on phone can't show code. Any suggestion or just simply // eslint-disable?
I'd need to see code to be certain.
Basically, outside of interface things a framework requires (like React component methods), things should only be instance methods if they need this - otherwise they should be static methods, or closed-over functions.
@ljharb code added
// Warning here, expected "this" to be used in class method 'renderScene'
renderScene(route, navigator) {
switch (route.id) {
case 'Home':
return <Home />;
case 'Cart':
return <Cart />;
case 'Settings':
return <Settings />;
default:
return <Main navigator={navigator} {...route.passProps} />;
}
}
render() {
return (
<Navigator
initialRoute={{ id: 'App' }}
renderScene={this.renderScene}
/>
);
}
That seems like a great use case for a separate function or a static method. Is there any reason it needs to be an instance method?
Put another way - is that a special method in React Native? If so, it belongs on the instance - if not, it doesn't.
It doesn't need to be instance and not a special method too.
I made it to static method and now works fine but 1 more question.
In es6 instead of calling ClassName.renderScene within class. Any other keyword i can use?
this.renderScene doesn't work
Anyway, this is fixed. Thanks again.
Using the hardcoded class name is the most reliable.
To answer your question @vzhen you can also use this.constructor.renderScene.
What are your thoughts on this approach @ljharb - is it ever used @airbnb?
You should never use the constructor property; it's not reliably present nor is it robust against tampering. Since there's no language keyword to mean "the current class", you should simply hardcode it.
I recently came across the new.target property which reminded me of this discussion - is the new.target property be robust enough to be used to refer to the current class?
It can't be fully polyfilled or transpiled, so no, it's not robust enough. Separately, it would only work inside the constructor itself.
Most helpful comment
I'd need to see code to be certain.
Basically, outside of interface things a framework requires (like React component methods), things should only be instance methods if they need
this- otherwise they should be static methods, or closed-over functions.