[React-Native]RN組件學習-Navigator

這是一個控制視圖跳轉(zhuǎn)的組件(類似于Android原生中的Activity之間的跳轉(zhuǎn))

自己的理解和實踐

RN會先加載index.android.js中的組件,這樣,我們就在該文件中只實現(xiàn)路由的跳轉(zhuǎn)。

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參數(shù),并在MyScene中通過props使用。

這樣,每次新建一個視圖的的時候,只要在跳轉(zhuǎn)的時候,指明其index就行了。

Note:
外部定義需要引入的class需要被export default進行修飾

監(jiān)聽后退按鍵

   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;
                            }
                            ....
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容