My main navigation component looks like this:
class Main extends React.Component {
constructor() {
super();
this.state = {
views: [
{ title: 'Page 1', component: React.createElement(PageOne) },
{ title: 'Page 2', component: React.createElement(PageTwo) },
{ title: 'Page 3', component: React.createElement(PageThree) }
],
currentView: 'Page 1'
};
}
changeScene(data) {
if (this.refs.navigator.getCurrentRoutes().find(r => r.title === data.title))
this.refs.navigator.jumpTo(data);
else
this.refs.navigator.push(data);
this.setState({currentView: data.title});
}
renderScene(route, navigator) {
return route.component;
}
render() {
return (
<View>
<Navigator
ref="navigator"
style={{flex: 1}}
initialRoute={this.state.views[0]}
renderScene={this.renderScene} />
</View>
);
}
};
I would like to call a method (something like onTransitionedTo
) on a Page component once it is transitioned to in the Navigator. I tried the following:
changeScene(data) {
if (this.refs.navigator.getCurrentRoutes().find(r => r.title === data.title))
this.refs.navigator.jumpTo(data);
else
this.refs.navigator.push(data);
this.setState({currentView: data.title});
if (data.component.onTransitionedTo)
data.component.onTransitionedTo();
}
But that obviously doesn't work. What would be the best way to accomplish this?
Perhaps try executing a passed callback on componentWillMount or some other appropriate lifecycle method so that the component is the one that checks if it's been transitioned to rather than the parent trying to execute something on the child directly.
In Main:
React.createElement(PageOne, { isActive: () => this._isActive(PageOne) })
...
_isActive(component) {
let routes = this.refs.navigator.getCurrentRoutes();
return component === routes[routes.length - 1];
}
In component:
componentWillMount() {
if (this.props.isActive()) {
// Set state to affect render
}
}
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.