Reputation: 10837
I want to call a method from the component (scene) that the Navigator has instantiated once the onDidFocus()
function is called.
This is how I instantiate the Navigator:
<Navigator
initialRoute={{ name: 'Login' }}
renderScene={ this.renderScene }
configureScene={(route, routeStack) => Navigator.SceneConfigs.FloatFromRight}
onDidFocus={(route) => route.component.onFocus()}
/>
And this is my renderScene()
method:
renderScene(route, navigator) {
if(route.name == 'Login') {
route.component = <Login navigator={navigator} {...route.passProps} />
}
return route.component
}
But route.component.onFocus()
is undefined
since (I presume) route.component
is not a reference to the instance that was mounted of Login
but a reference to the type Login
.
So how can I get a reference to the instance of the component that was mounted?
How can I call a method of the component that has been mounted when the onDidFocus()
method is called?
Upvotes: 2
Views: 1211
Reputation: 10837
Like @farwayer suggested, calling a function from the component is bad practice since it's coupled code.
In the end I used our own Event Bus to notify any interested party that the transition had ended.
onDidFocus(){
EventBus.ref().emit('NAVIGATOR_TRANSITION_END')
}
render() {
return (
<Navigator
...
onDidFocus={ this.onDidFocus }
/>
)
}
Upvotes: 1
Reputation: 4122
Calling component methods directly is a bad practice. If you simply want to catch moment when component activated you can override componentDidMount()
method.
Or in more complex situation you can call setState()
in parent component and pass new props to Login
. Something like this:
<Navigator
initialRoute={{ name: 'Login' }}
renderScene={ this.renderScene }
configureScene={(route, routeStack) => Navigator.SceneConfigs.FloatFromRight}
onDidFocus={(route) => this.setState({currentRoute: route})} />
renderScene(route, navigator) {
return <Login
currentRoute={this.state.currentRoute}
navigator={navigator}
{...route.passProps} />
}
and then catch new props in Login
component with overriding componentWillReceiveProps()
.
Upvotes: 1