RN项目之react-Navigation(路由导航)

RN项目之Navigation

		react navigation地址:https://reactnavigation.org/
		在任何一个项目都离不开路由、关于RN的路由总结以下几点
	一、**基本**	
  1. 首先安装基本模块npm install @react-navigation/native -Syarn add @react-navigation/native
  2. 然后再安装npm install @react-navigation/stack
  3. 使用
			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

  1. 当想要改变header时、可以使用this.props.navigation.setOptions({title:})
  2. 当后代组件想要使用navigation 可以通过context传递
Index.jsx中  上个面已经使用screen定义了、此时props中含有navigation

 <Provider value={{...this.props}}>
 
<子组件>

// 此时子组件可以通过cunsumer消费navigation
 </Provider>
  1. 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/

发布了4 篇原创文章 · 获赞 6 · 访问量 127

猜你喜欢

转载自blog.csdn.net/F_efforts/article/details/104409131