React Native Navigation路由学习(一)

1,069 阅读2分钟

RN中的界面跳转是由路由来完成的,官方文档:reactnavigation.org/docs/7.x/na…

1、导入三方库

"@react-navigation/native": "6.1.0",
"@react-navigation/native-stack": "6.1.0",

2、创建栈路由

const Stack = createNativeStackNavigator();

3、在路由容器中,放入栈路由

<NavigationContainer> 
    <Stack.Navigator initialRouteName={"Home"}>
        <Stack.Screen name="Home">
            {props => <LoginView {...props} extraData={{title:"你好"}} />} 
        </Stack.Screen> 
        <Stack.Screen name="Detail" component={DetailScreen} /> 
    </Stack.Navigator> 
</NavigationContainer>

initialRouteName 属性是必填属性

需要使用此路由跳转的界面,都需要作为此路由的children在底下注册,路由的props,会作为参数传入到children中

注意:{...props} 的这种写法 ,表示拼接,即 props 里面所有的属性,会作为参数和 extraData 拼接在一起,作为 LoginView的 props属性

<Text> 你好,这是登录界面 {props.extraData.title} </Text>
<TouchableOpacity 
    style={{ backgroundColor: "red", width:100, height:30 }} 
    onPress={() => { 
        props.navigation.navigate("Detail") 
    }}>
</TouchableOpacity>

在LoginView中可以看到,navigation和extraData都是props下的属性,借此来理解 {...props} 这种写法的作用。

image.png

4、页面跳转

页面跳转需要使用navigation工具来完成,传入的参数为 在根路由下面注册的 界面名字

props.navigation.navigate("Detail")
props.navigation.push("Detail")

push对应Android中的标准启动模式

navagate是从栈顶开始往里找到对应的界面,然后跳过去(类似SingleTop)

5、参数传递

即在界面跳转的时候带上参数给下个界面

<TouchableOpacity onPress={()=>{ navigation.navigate("Home",{ title:"水水水水" })

在Home界面,我们可以使用route来获取接收的参数

<Text> 你好,这是登录界面 {props.extraData.title} {props.route.params?.title} </Text>

image.png

退回上个界面并携带参数,类似安卓中 StartActForResult 场景。

界面A -> 界面B ,B操作完成之后,退回到A界面,并将一些数据携带给A。

× 不能使用上面的naviage(A,{参数})的方法,此方法会将A原有的 route 对象替换掉,导致A原有数据丢失。

应该使用下面这种方法,naviage({name:A,merge:true,params:{参数}}),注意merge为true,此方法会把 content 合并到 A界面原有的 route中去。

navigation.navigate({ 
    name:"Home",
    params:{content:"this is a content"},
    merge:true 
})

在A界面中, 我们同样使用route来接受 B返回的值即可。

<Text> 你好,这是登录界面 
{props.extraData.title}
{props.route.params?.title} // A原有route 中的属性 
{props.route.params?.content} // B传递给A的属性,被合并到route中去了,也通过route来获取即可 
</Text>

image.png

6、设置Header Bar

默认的header bar为一个Text,文字内容为 注册时候的 name

image.png

设置自定义的Header bar,有两种方式。

第一种方式需要在注册的位置添加options参数

<Stack.Screen 
    name="Home"
    options={{ title: "这是首页" }}> 
        {(props) => { 
            return <LoginView {...props} extraData={{ title: "你好" }}
        /> } } 
</Stack.Screen>

image.png

在注册的位置不止可以添加对象参数,还可以添加函数参数,可以从navigation的参数中去读取数据作为options的数据

<Stack.Screen 
    name="Home" 
    options={({route})=>{return {title:route.params?.title}}}> 
        {(props) => { return <LoginView {...props} extraData={{ title: "你好" }} /> }} 
</Stack.Screen>

image.png

第二种方式是使用navigation.setOptions方法,来设置

React.useEffect(() => {
    navigation.setOptions({ 
        title: 'Updated!' , 
        headerRight:()=>{
            return <Text style={{color:"red"}}>右边的文字</Text> 
            } 
        }) 
}, [navigation])

image.png

关于header bar的更多设置,可以参考 reactnavigation.org/docs/native…