美文网首页
[React-Native]RN组件学习-Navigator

[React-Native]RN组件学习-Navigator

作者: 美乃滋酱啊 | 来源:发表于2016-08-09 17:36 被阅读35次

这是一个控制视图跳转的组件(类似于Android原生中的Activity之间的跳转)

自己的理解和实践

RN会先加载index.android.js中的组件,这样,我们就在该文件中只实现路由的跳转。

index.android.js

export default class StudyNavigationApp extends Component {
  render() {
    return (
      <Navigator
        initialRoute={{title:'My initial Scene',index:0}}
        renderScene={(route,navigator)=>{
              switch (route.index){
                case 0:
                  return <MyScene navigator={navigator}/>
                  break;
                case 1:
                  return <ComponentStudy0 navigator={navigator}/>
                  break;
              }
            }
          }
      />
    );
  }
}

这里我们默认了index为0的时候需要加载MyScene

class MyScene extends Component {
  render() {
    return (
       <View>
        <TouchableHighlight onPress={()=>this.props.navigator.push({index:1})}>
          <Text>
            Hi,My name is hehe
          </Text>
        </TouchableHighlight>
      </View>
    )
  }
}

在上面的默认加载index为0的时候加载MyScene的时候,传入了navigator参数,并在MyScene中通过props使用。

这样,每次新建一个视图的的时候,只要在跳转的时候,指明其index就行了。

Note:
外部定义需要引入的class需要被export default进行修饰

监听后退按键

   constructor(props) {
        super(props);
        this.goBack = this.goBack.bind(this);
    }

    componentDidMount() {
        BackAndroid.addEventListener('hardwareBackPress', this.goBack);
    }

    componentWillUnMount() {
        BackAndroid.removeEventListener('hardwareBackPress', this.goBack);
    }

当然,你需要先引入BackAndroid,然后在Navigator的属性renderScene中实例化_navigator.

<Navigator
                initialRoute={{title:'RN study',index:0}}
                renderScene={(route,navigator)=>{
                            _navigator = navigator;
                            }
                            ....

相关文章

网友评论

      本文标题:[React-Native]RN组件学习-Navigator

      本文链接:https://www.haomeiwen.com/subject/mhedsttx.html