react-navigaton3.x之createStackNa
2019-07-17 本文已影响0人
LD_左岸
0.RN版本信息

1.安装插件
1.1初始化项目
react-native init XXX --version 0.59.0

1.2 启动项目

1.3 开启实时刷新服务

1.4 安装react-navigation
yarn add react-navigation

1.5 安装react-native-gesture-handler

1.6 link

代码书写
2.1 设置Home导航容器为App的根容器
在index中修改App为Home
/**
* @format
*/
import React from 'react'
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import Home from './navigators/pages/Home'
AppRegistry.registerComponent(appName, () => Home);
2.2配置Home的导航容器
import {
createStackNavigator,
createAppContainer
} from 'react-navigation'
import React from 'react'
import {View, Button} from 'react-native'
import first from './first'
import second from './second'
const Home = createStackNavigator({
first:{
screen:first,
navigationOptions:{
title:`First`,
headerBackTitle:`返回`
}
},
second:{
screen:second,
navigationOptions: {
title: `Second`
}
}
});
export default HomeNav = createAppContainer(Home)
2.3 用于跳转的两个界面
first
import React,{Component} from 'react'
import {View,Text, Button} from 'react-native'
export default class first extends Component{
render(){
const {navigation} = this.props;
return <View>
<Text>First</Text>
{/*写法一不传值*/}
<Button title='跳转二级界面' onPress={()=>{
navigation.push('second')
}}></Button>
{/*写法二传值*/}
<Button title='跳转二级界面传值'
onPress={() => navigation.navigate('second', {name: 'LDD'})}
>
</Button>
</View>
}
}
*********************************************************
second
import React,{Component} from 'react'
import {View,Text, Button} from 'react-native'
export default class second extends Component{
render(){
const {navigation} = this.props;
return <View>
<Text>First</Text>
<Button title='返回一级界面' onPress={()=>{
navigation.pop();
}}></Button>
<Text>{'一级界面传递过来的name的值 = ' + navigation.state.params.name}</Text>
</View>
}
}
second 通过setParams 改变当前页面naviagtion中的state.params的值
import React,{Component} from 'react'
import {View,Text, Button} from 'react-native'
export default class second extends Component{
render(){
const {navigation} = this.props;
// console.warn(navigation.state.params);
const {setParams} = this.props.navigation;
return <View>
<Text>First</Text>
<Button title='返回一级界面' onPress={()=>{
//navigation.pop();
navigation.goBack();
}}>
</Button>
{/*使用setParams改变 route params*/}
<Button
onPress={()=>setParams({name:'不能等于LDD了'})}
title="setParams to '非LDD'"
>
</Button>
<Text>{'一级界面传递过来的name的值 = ' + navigation.state.params.name}</Text>
</View>
}
}