ReactNative導航的右邊新增按鈕做跳轉

weixin_33850890發表於2017-06-30

ReactNative 棧導航(StackNavigator):
第一步引入import {StackNavigator} from 'react-navigation';
第二步:建立元件設定navigationOptions
第三步:StackNavigator 配置螢幕
(1.需要做跳轉的其他元件時需要通過props獲取navigate ,
const {navigate}=this.props.navigation,然後在跳轉事件裡面呼叫navigator('傳入要跳轉螢幕對應的key')
2.如果在navigationOptions裡面做跳轉則需要吧{navigation}傳進去,然後代用navigation.navigate('傳入要跳轉螢幕對應的key'),如下:
在導航的右邊新增headerRight 重點是把navigation傳進去,比如

static navigationOptions=({navigation})=>({

title:'Title',

headerRight:<Button title='right' onPress={()=>navigation.navigate('這裡是指向的元件key')}/>

});
3.需要傳引數的時候在navigate(引數一是路由名字,引數二dict傳值)
navigate('Chat',{user:'abc'})
取引數的時候 需要 const {params} = this.props.navigation.state.
比如:const {params} = this.props.navigation.state;
return <Text>Chat with{params.user}</Text>
如果是在navigationOptions取引數
比如 static navigationOptions =({navigation})=>({
title:${navigation.state.params.user},
}
)
//)。
···
/**

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
Dimensions,
TextInput,
ScrollView,
FlatList,
SectionList,
Button
} from 'react-native';

import {StackNavigator} from 'react-navigation';

class HomeScreen extends Component{
static navigationOptions =({navigation})=>({
title:'Main',
headerRight:<Button title="Right" onPress={()=>navigation.navigate('Sec',{user:'Lucy'})}/>,
}) ;
render(){
const {navigate} = this.props.navigation;
return(
<View>
<Text>this is Main</Text>
<Button title="Second" onPress={()=>navigate('Sec',{user:'Lucy'})}/>
</View>
);
}

}
class Second extends Component{
static navigationOptions =({navigation})=>( {
title:Chat with ${navigation.state.params.user},
});
render(){
const {params} = this.props.navigation.state;
return(
<Text>chat with {params.user}</Text>
);
}
}
const App = StackNavigator({
Home:{screen:HomeScreen},
Sec:{screen:Second}
});

var screenWidth =Dimensions.get('window').width;
const styles = StyleSheet.create({

container:{
    flex:1,
    marginTop:20,

},
text:{
    flex:1,
    justifyContent:'center',
    alignItems:'center',
    textAlign:'center',
    backgroundColor:'red',
},

});

AppRegistry.registerComponent('AwesomeProject', () => App);
···

相關文章