6.1 Navigator

1.define routes

  1. import MainTabsView from './MainTabsView';
  2. import EditView from './EditView';
  3. import BroswerView from './BroswerView';
  4. const ROUTES = { MainTabsView, BroswerView, EditView };

2.config Navigator

  1. class App extends Component {
  2. renderScene = (route, navigator) => {
  3. let Scene = ROUTES[route.name];
  4. return <Scene {...route} navigator={navigator}/>;
  5. }
  6. configureScene = (route, routeStack) => {
  7. switch (route.name){
  8. case 'EditView':
  9. return Navigator.SceneConfigs.FloatFromBottom;
  10. default:
  11. return Navigator.SceneConfigs.PushFromRight;
  12. }
  13. }
  14. render() {
  15. return (
  16. <View style={styles.container}>
  17. <StatusBar barStyle="light-content"/>
  18. <Navigator
  19. initialRoute={{name: 'MainTabsView'}}
  20. renderScene={this.renderScene}
  21. configureScene={this.configureScene}/>
  22. </View>
  23. )
  24. }
  25. }

3.forward & back

 6.1 Navigator  - 图1

  1. ...
  2. handleEdit = ()=>{
  3. //Navigate forward to a new scene
  4. this.props.navigator.push({name: 'EditView', data: this.props.data});
  5. }
  6. ...
  1. ...
  2. close = ()=>{
  3. //Transition back and unmount the current scene
  4. this.props.navigator.pop();
  5. }
  6. ...

 6.1 Navigator  - 图2

4.onDidFocus & onWillFocus

  1. ...
  2. componentDidMount(){
  3. this.currentRoute = this.props.navigator.navigationContext.currentRoute;
  4. this.bindEvents();
  5. }
  6. componentWillUnmount(){
  7. this.unBindEvents();
  8. }
  9. bindEvents = ()=>{
  10. this.willFocusSubscription = this.props.navigator.navigationContext.addListener('willfocus', (event) => {
  11. if (this.currentRoute !== event.data.route) {
  12. this.setState({isVisible: false});
  13. }
  14. });
  15. this.didFocusSubscription = this.props.navigator.navigationContext.addListener('didfocus', (event) => {
  16. if (this.currentRoute === event.data.route) {
  17. this.setState({isVisible: true});
  18. }
  19. });
  20. }
  21. unBindEvents = ()=>{
  22. this.willFocusSubscription.remove();
  23. this.didFocusSubscription.remove();
  24. }
  25. ...

原文: https://unbug.gitbooks.io/react-native-training/content/61_navigator.html