React Native入门(九)之导航组件React Navigation(1)StackNa
前言本篇文章了解一下RN中导航组件的使用,且使用的是官方推荐的一个单独的导航库 使用安装react-navigation库首先呢,这个库是单独的,所以需要我们把这个库添加到我们的项目中去,在我们的项目目录执行: yarn add react-navigation
StackNavigator使用这个导航组件主要用于不同页面之间的切换!,这个非常类似于Android中的Intent,来进行不同页面的挑战和数据的传值! //首先需要将StackNavigator引入
import {
StackNavigator,} from 'react-navigation';
class MainScreen extends Component{
//设置navigationOptions
static navigationOptions = {
title: '主页面',//标题
};
render() {
//navigation属性
const { navigate } = this.props.navigation;
return (
<View> <Text style={{fontSize:20}}>我是MainScreen!</Text> <Button title="跳到SecondScreen" //点击跳转,参数为下边RouteConfigs中要跳转的routeName onPress={()=>navigate('Sencond')}/> </View> ); } } class SecondScreen extends Component{ static navigationOptions ={ title: 次页面 }; render() { return ( <View > <Text style={{fontSize:20}}>我是SecondScreen!</Text> </View> ); } } //设置StackNavigator(RouteConfigs,StackNavigatorConfig) const App = StackNavigator({ Main: {screen: MainScreen},Sencond: {screen: SecondScreen},}); AppRegistry.registerComponent('AwesomeProject',() => App);
上边就是StackNavigator的基本用法,如果要在页面跳转的时候传递一些数据要这样写: onPress={()=>navigate('Sencond',{ hello: '你好!' })}
在 render() { const { params } = this.props.navigation.state; return ( <View > <Text style={{fontSize:20}}>{params.hello}我是SecondScreen!</Text> </View> ); }
要先拿到传值页面中navigation属性的state: 另外如果我们在第二个接收页面设置 static navigationOptions = ({ navigation }) => ({
title: `次页面 ${navigation.state.params.hello}`,});
可以将 StackNavigator({
Main: {screen: MainScreen},Sencond: {
screen: SecondScreen,navigationOptions: ({navigation}) => ({
title: `次页面 ${navigation.state.params.hello}`,}),},});
直接在配置第二个页面的RouteConfigs时,去设置 可以试一下: class SecondScreen extends Component{
static navigationOptions = {
title: '我就不信我显示不了!',};
...
}
运行一下: 配置那么说到这里,我们在设置StackNavigator的时候都可以设置哪些东东? StackNavigator(RouteConfigs,StackNavigatorConfig)
RouteConfigs:路由设置这里参照官网: StackNavigator({
// For each screen that you can navigate to,create a new entry like this: //路由名字 Profile: { // `ProfileScreen` is a React component that will be the main content of the screen. //具体的页面 screen: ProfileScreen,// When `ProfileScreen` is loaded by the StackNavigator,it will be given a `navigation` prop. // Optional: When deep linking or using react-navigation in a web app,this path is used: //页面的路径 path: 'people/:name',// The action and route params are extracted from the path. // Optional: Override the `navigationOptions` for the screen //导航栏选项 navigationOptions: ({navigation}) => ({ title: `${navigation.state.params.name}'s Profile'`,...MyOtherRoutes,});
StackNavigatorConfigOptions for the router:
还有一些视觉效果上面的配置,比如设置页面切换模式 navigationOptions导航栏选项那么具体到一个页面中,navigationOptions都可以设置哪些参数?
其他的属性参数的设置,就不再说了,可以参考官方文档: 结语本篇文章主要介绍了React Navigation导航库中StackNavigator的使用,剩余的两个导航组件,我们放在下篇博客中了解! 好了,就这样,我们下篇文章再见! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |