REACT NAVIGATION August 29, 2018

【React Navigation】三、屏幕切换

Words count 7.8k Reading time 7 mins. Read count 0

在上一个环节中,我们定义了一个包含了两个路由的堆栈导航器,但我们还没有实现让导航器从Home路由跳转到Details路由。(虽然我们确实学习了如何在我们的代码中更改初始路由,但是为了看到另外一个路由,需要我们的用户在代码中更改初始路由,这是一种糟糕的用户体验)

假如是浏览器,我们可以通过以下写法来达到页面跳转

1
2
3
<a href="details.html">Go to Details</a>
或者
<a onClick={() => { document.location.href = "details.html"; }}>Go to Details</a>

接下来我们将通过navigation的属性来实现导航器的页面跳转

导航到新页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React from 'react';
import { Button, View, Text } from 'react-native';
import { createStackNavigator } from 'react-navigation';

class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}
/>
</View>
);
}
}

// ... other code from the previous section

重点:

  1. this.props.navigation:navigation属性将被传递到每个在堆栈导航器中定义的屏幕组件中
  2. navigate(‘Details’):通过调用navigate方法,并传入我们想跳转的页面名称来实现指定的页面跳转

假如navigate中传入的页面名称没有在堆栈导航器中定义,则不会执行任何操作。另外,我们只能跳转到堆栈导航器中定义的页面去

假如我们从Details页面再一次跳转到Details界面会发生什么情况呢?

多次跳转到同一个页面

1
2
3
4
5
6
7
8
9
10
11
12
13
class DetailsScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Button
title="Go to Details... again"
onPress={() => this.props.navigation.navigate('Details')}
/>
</View>
);
}
}

执行该代码,我们可以发现,页面不会产生变化。假如我们当前已经跳转到指定的页面,则再一次调用navigate跳转到该页面,不会产生任何的效果。

假如我们真的有这样的需求呢?我们可以使用push函数来替换原有的navigate函数,该函数允许我们创建一个新的路由线路而忽略原来的

1
2
3
4
5
<Button
title="Go to Details... again"
onPress={() => this.props.navigation.push('Details')}
/>
}

页面回退

堆栈导航器提供的标题栏会自动包含一个后退按钮,它允许我们返回到上一个页面(如果堆栈导航器只有一个屏幕,则没有任何内容可以返回,因此没有返回键)。

有时你希望能够以编程方式触发此行为,可以使用this.props.navigation.goBack()函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class DetailsScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Button
title="Go to Details... again"
onPress={() => this.props.navigation.push('Details')}
/>
<Button
title="Go to Home"
onPress={() => this.props.navigation.navigate('Home')}
/>
<Button
title="Go back"
onPress={() => this.props.navigation.goBack()}
/>
</View>
);
}
}

还有另外一些常见的需求:能够直接返回到前几个页面去。例如,你已经跳转了好几层页面(A->B->C->D),现在想要直接返回到A,可以直接使用navigate(‘A’)。或者使用navigation.popToTop(),它返回到堆栈中的第一个页面(A)

0%