RN项目之Navigation
react navigation地址:https://reactnavigation.org/
在任何一个项目都离不开路由、关于RN的路由总结以下几点
一、**基本**
- 首先安装基本模块
npm install @react-navigation/native -S
或yarn add @react-navigation/native
- 然后再安装
npm install @react-navigation/stack
- 使用
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
//组件定义好以后
const Stack = createStackNavigator()
export default function App() {
return (
<NavigationContainer>
<Provider store={store}> //当需要使用状态管理时、Provider可以写在第二层
<Stack.Navigator
initialRouteName="Index" //作为初始化页面、不写的话默认第一个screen为初始化页面
screenOptions={{ //用来定制头部信息、根据自己需要更改
title: '美食大全',
headerStyle: {
backgroundColor: '#ee7530'
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
fontSize: 20
}
}}
>
<Stack.Screen //真正定义路由的内容
name="Index"
component={Index}
options={{
title: '首页'
}}
/>
</Stack.Navigator>
</Provider>
</NavigationContainer>
)
}
·里面可以嵌套多个screen 其中screen所必需的属性 name=“Index” component={Index}
name:引用路由的名称
component是对应组件
二、在组件中使用navigation
这里有一点需要注意、只有在screen中的组件、才能获取到navigation、通过this.props.navigation
- 当想要改变header时、可以使用this.props.navigation.setOptions({title:})
- 当后代组件想要使用navigation 可以通过context传递
Index.jsx中 上个面已经使用screen定义了、此时props中含有navigation
<Provider value={{...this.props}}>
<子组件>
// 此时子组件可以通过cunsumer消费navigation
</Provider>
- navigation传参
navigation.push()或
navigation.navigate()
navigation.push('名字',{title:“信息”}) //这个名字是screen中的name
跳转到的组件取值时注意:通过navigation跳转过来、props中含有route一个属性
this.props.route.params()就是传来的数据
然后可以通过this.props.navigation.setOptions({title:})二次设置头部信息(根据自身业务)
详细内容可见react navigation地址:https://reactnavigation.org/