如何在 React Native 中使用 React Navigation 路由功能

介绍

React Navigation是用于在 React Native应用程序中路由和导航的流行的库。

此库有助于解决在多个屏幕之间导航和共享数据的问题。

在本教程结束时,你将有一个基本的社交网络. 它将显示用户的连接数量,并提供与其他朋友连接的方法. 你将使用这个样本应用程序来探索如何使用反应导航导航移动应用程序屏幕。

前提条件

要完成本教程,您将需要:

<$>[注] 注: 如果您在过去曾使用过反应导航,您可能会遇到一些差异。您可以在 从 3.x 迁移从 4.x 迁移上查阅指南的文档。

本教程已通过 Node v14.7.0、npm v6.14.7、react v16.13.1、react-native v0.63.2、@react-navigation/native v5.7.3 和@react-navigation/stack v5.9.0 进行验证。

步骤 1 – 创建一个新的 React Native 应用程序

首先,通过在终端中输入以下命令创建一个新的 React Native 应用程序:

1npx react-native init MySocialNetwork --version 0.63.2

然后,导航到新目录:

1cd MySocialNetwork

然后为 iOS 启动应用程序:

1npm run ios

此外,对于Android来说:

1npm run android

<$>[注] 注: 如果您遇到任何问题,您可能需要查阅 React Native CLI 的故障排除问题(https://reactnative.dev/docs/environment-setup)。

这将为您创建一个骨骼项目. 它现在看起来不像一个社交网络。

打开App.js:

1nano App.js

用以下代码取代App.js的内容,以显示欢迎消息:

 1[label App.js]
 2import React from 'react';
 3import { StyleSheet, Text, View } from 'react-native';
 4
 5class App extends React.Component {
 6  render() {
 7    return (
 8      <View style={styles.container}>
 9        <Text>Welcome to MySocialNetwork!</Text>
10      </View>
11    );
12  }
13}
14
15const styles = StyleSheet.create({
16  container: {
17    flex: 1,
18    backgroundColor: '#fff',
19    alignItems: 'center',
20    justifyContent: 'center',
21  },
22});
23
24export default App;

现在,当你运行应用程序时,在你的模拟器中会出现一个 **Welcome to MySocialNetwork!**消息。

在下一步中,您将为您的应用程序添加更多的屏幕。

步骤 2 — 创建一个主屏朋友屏

在此步骤中,您将为您的应用程序创建两个屏幕:‘HomeScreen’和‘FriendsScreen’。

《HomeScreen》

您的应用程序将需要一个主屏幕主屏幕将显示已经在您的网络中的朋友数量。

App.js中取代代码,并将其添加到名为HomeScreen.js的新文件中:

1cp App.js HomeScreen.js

打开HomeScreen.js:

1nano HomeScreen.js

更改HomeScreen.js以使用HomeScreen而不是App:

 1[label HomeScreen.js]
 2import React from 'react';
 3import { StyleSheet, Text, View } from 'react-native';
 4
 5class HomeScreen extends React.Component {
 6  render() {
 7    return (
 8      <View style={styles.container}>
 9        <Text>You have (undefined) friends.</Text>
10      </View>
11    );
12  }
13}
14
15// ...
16
17export default HomeScreen;

此代码将生成一个 ** 你有(未定义)的朋友. ** 位置持有人消息. 您将稍后提供一个值。

《友情屏幕》

你的应用程序还需要一个FriendsScreen。在FriendsScreen上,你将能够添加新的朋友。

App.js中取代代码,并将其添加到名为FriendsScreen.js的新文件中:

1cp App.js FriendsScreen.js

打开FriendsScreen.js:

1nano FriendsScreen.js

更改「FriendsScreen.js」以使用「FriendsScreen」而不是「App」:

 1[label FriendsScreen.js]
 2import React from 'react';
 3import { StyleSheet, Text, View } from 'react-native';
 4
 5class FriendsScreen extends React.Component {
 6  render() {
 7    return (
 8      <View style={styles.container}>
 9        <Text>Add friends here!</Text>
10      </View>
11    );
12  }
13}
14
15// ...
16
17export default FriendsScreen;

此代码会产生一个 ** 添加朋友! ** 消息。

在此时,您有主屏幕朋友屏幕。然而,您无法在它们之间进行导航,您将在下一步建立此功能。

步骤 3 — 使用StackNavigator与 React 导航

要在屏幕之间进行导航,你会使用一个StackNavigator。一个StackNavigator就像一个 呼叫堆栈。你导航的每个屏幕都被推到堆栈的顶部。

首先,安装@react-navigation/native:

1npm install @react-navigation/[email protected]

然后,安装@react-navigation/stack及其对等依赖:

1npm install @react-navigation/[email protected] @react-native-community/[email protected] [email protected] [email protected] [email protected]

<$>[注] 注: 如果您正在为 iOS 开发,您可能需要导航到ios目录并运行pod install <$>

接下来,重新浏览App.js:

1nano App.js

NavigationContainercreateStackNavigator添加到App.js:

1[label App.js]
2import 'react-native-gesture-handler';
3import React from 'react';
4import { StyleSheet } from 'react-native';
5import { NavigationContainer } from '@react-navigation/native';
6import { createStackNavigator } from '@react-navigation/stack';
7
8const Stack = createStackNavigator();

然后,替换交付的内容:

 1[label App.js]
 2// ...
 3
 4class App extends React.Component {
 5  render() {
 6    return (
 7      <NavigationContainer>
 8        <Stack.Navigator>
 9        </Stack.Navigator>
10      </NavigationContainer>
11    );
12  }
13}
14
15// ...

<Stack.Navigator>里面,添加HomeScreen:

 1[label App.js]
 2import 'react-native-gesture-handler';
 3import React from 'react';
 4import { StyleSheet } from 'react-native';
 5import { NavigationContainer } from '@react-navigation/native';
 6import { createStackNavigator } from '@react-navigation/stack';
 7import HomeScreen from './HomeScreen';
 8
 9const Stack = createStackNavigator();
10
11class App extends React.Component {
12  render() {
13    return (
14      <NavigationContainer>
15        <Stack.Navigator>
16          <Stack.Screen
17            name="Home"
18            component={HomeScreen}
19          />
20        </Stack.Navigator>
21      </NavigationContainer>
22    );
23  }
24}
25
26// ...

此代码为您的导航器创建了一个非常小的堆栈,只有一个屏幕:主屏幕

Stack.Navigator里面,添加FriendsScreen:

 1[label App.js]
 2import 'react-native-gesture-handler';
 3import React from 'react';
 4import { StyleSheet } from 'react-native';
 5import { NavigationContainer } from '@react-navigation/native';
 6import { createStackNavigator } from '@react-navigation/stack';
 7import HomeScreen from './HomeScreen';
 8import FriendsScreen from './FriendsScreen';
 9
10const Stack = createStackNavigator();
11
12class App extends React.Component {
13  render() {
14    return (
15      <NavigationContainer>
16        <Stack.Navigator>
17          <Stack.Screen
18            name="Home"
19            component={HomeScreen}
20          />
21          <Stack.Screen
22            name="Friends"
23            component={FriendsScreen}
24          />
25        </Stack.Navigator>
26      </NavigationContainer>
27    );
28  }
29}
30
31// ...

此代码将FriendsScreen添加到导航器中。

<$>[注] 注: 这与在 React Navigation 以前版本中使用的createStackNavigator方式不同。

现在,导航器知道你的两个屏幕。

主屏幕朋友屏幕中添加按钮

最后,添加按钮,将你带到你的两个屏幕之间。

HomeScreen.js中,添加以下代码:

 1[label HomeScreen.js]
 2import React from 'react';
 3import { StyleSheet, Text, View, Button } from 'react-native';
 4
 5class HomeScreen extends React.Component {
 6  render() {
 7    return (
 8      <View style={styles.container}>
 9        <Text>You have (undefined) friends.</Text>
10
11        <Button
12          title="Add some friends"
13          onPress={() =>
14            this.props.navigation.navigate('Friends')
15          }
16        />
17      </View>
18    );
19  }
20}
21
22// ...

FriendsScreen.js中,添加以下代码:

 1[label FriendsScreen.js]
 2import React from 'react';
 3import { StyleSheet, Text, View, Button } from 'react-native';
 4
 5class FriendsScreen extends React.Component {
 6  render() {
 7    return (
 8      <View style={styles.container}>
 9        <Text>Add friends here!</Text>
10
11        <Button
12          title="Back to home"
13          onPress={() =>
14            this.props.navigation.navigate('Home')
15          }
16        />
17      </View>
18    );
19  }
20}
21
22// ...

只要你的屏幕包含在StackNavigator中,它会自动继承navigation对象的许多有用的副本。

HomeScreen and FriendsScreen

如果您现在打开模拟器,您可以在主屏朋友屏之间导航。

步骤 4 – 使用背景将数据传输到其他屏幕

在此步骤中,您将创建一组可能的朋友 - 爱丽丝, 鲍勃萨米 - 以及一组空的现有朋友。

打开App.js:

1nano App.js

possibleFriendscurrentFriends添加到组件的状态:

 1[label App.js]
 2// ...
 3
 4class App extends React.Component {
 5  constructor(props) {
 6    super(props)
 7    this.state = {
 8      possibleFriends: [
 9        'Alice',
10        'Bob',
11        'Sammy',
12      ],
13      currentFriends: [],
14    }
15  }
16
17  // ...
18}
19
20// ...

接下来,添加一个函数来将可能的朋友移动到当前的朋友列表:

 1[label App.js]
 2// ...
 3
 4class App extends React.Component {
 5  constructor(props) {
 6    super(props)
 7    this.state = {
 8      possibleFriends: [
 9        'Alice',
10        'Bob',
11        'Sammy',
12      ],
13      currentFriends: [],
14    }
15  }
16
17  addFriend = (index) => {
18    const {
19      currentFriends,
20      possibleFriends,
21    } = this.state
22
23    // Pull friend out of possibleFriends
24    const addedFriend = possibleFriends.splice(index, 1)
25
26    // And put friend in currentFriends
27    currentFriends.push(addedFriend)
28
29    // Finally, update the app state
30    this.setState({
31      currentFriends,
32      possibleFriends,
33    })
34  }
35
36  // ...
37}
38
39// ...

此时,你已经完成了添加朋友的功能。

FriendsContext添加到App

现在你可以在App.js中添加朋友,但你会想将他们添加到FriendsScreen.js,并在HomeScreen.js中显示。

<$>[注] **注:**在 React Navigation 之前的版本中,可以使用「screenProps」在屏幕之间共享数据,在当前版本的 React Navigation 中,建议使用 React Context在屏幕之间共享数据。

为了避免循环引用,您需要一个新的FriendsContext文件:

1nano FriendsContext.js

出口朋友背景:

1[label FriendsContext]
2import React from 'react';
3
4export const FriendsContext = React.createContext();

打开App.js:

1nano App.js

添加友情背景:

 1[label App.js]
 2import 'react-native-gesture-handler';
 3import React from 'react';
 4import { StyleSheet } from 'react-native';
 5import { NavigationContainer } from '@react-navigation/native';
 6import { createStackNavigator } from '@react-navigation/stack';
 7import { FriendsContext } from './FriendsContext';
 8import Home from './Home';
 9import Friends from './Friends';
10
11const Stack = createStackNavigator();
12
13class App extends React.Component {
14  // ...
15
16  render() {
17    return (
18      <FriendsContext.Provider>
19        <NavigationContainer>
20          <Stack.Navigator>
21            <Stack.Screen
22              name="Home"
23              component={Home}
24            />
25            <Stack.Screen
26              name="Friends"
27              component={Friends}
28            />
29          </Stack.Navigator>
30        </NavigationContainer>
31      </FriendsContext.Provider>
32    );
33  }
34}
35
36// ...

此代码将FriendsContext设置为新的Context对象(LINK0)并将NavigationContainer嵌入到Context.Provider组件中,以便组件树中的任何孩子都可以订阅背景更改。

由于您不再使用查看文本,因此可以将这些导入从反应原生中移除。

您需要提供一个,以使消费者可以访问数据:

 1[label App.js]
 2// ...
 3
 4class App extends React.Component {
 5  // ...
 6
 7  render() {
 8    return (
 9      <FriendsContext.Provider
10        value={
11          {
12            currentFriends: this.state.currentFriends,
13            possibleFriends: this.state.possibleFriends,
14            addFriend: this.addFriend
15          }
16        }
17      >
18        <NavigationContainer>
19          <Stack.Navigator>
20            <Stack.Screen
21              name="Home"
22              component={Home}
23            />
24            <Stack.Screen
25              name="Friends"
26              component={Friends}
27            />
28          </Stack.Navigator>
29        </NavigationContainer>
30      </FriendsContext.Provider>
31    );
32  }
33}
34
35// ...

这将允许HomeScreenFriendsScreen将任何背景变化参考为currentFriendspossibleFriends

现在你可以工作在你的屏幕上引用背景。

FriendsContext添加到HomeScreen

在此步骤中,您将设置应用程序以显示当前朋友数。

打开HomeScreen.js:

1nano HomeScreen.js

并添加友情背景:

 1[label HomeScreen.js]
 2import React from 'react';
 3import { StyleSheet, Text, View, Button } from 'react-native';
 4import { FriendsContext } from './FriendsContext';
 5
 6class HomeScreen extends React.Component {
 7  // ...
 8}
 9HomeScreen.contextType = FriendsContext;
10
11// ...

此代码设置了一个 Class.contextType

例如,让我们让您的主屏幕显示您有多少当前朋友:

 1[label HomeScreen.js]
 2import React from 'react';
 3import { StyleSheet, Text, View, Button } from 'react-native';
 4import { FriendsContext } from './FriendsContext';
 5
 6class Home extends React.Component {
 7  render() {
 8    return (
 9      <View style={styles.container}>
10        <Text>You have { this.context.currentFriends.length } friends!</Text>
11
12        <Button
13          title="Add some friends"
14          onPress={() =>
15            this.props.navigation.navigate('Friends')
16          }
17        />
18      </View>
19    );
20  }
21}
22HomeScreen.contextType = FriendsContext;
23
24// ...

如果您在模拟器中重新打开应用程序并查看主屏幕,您将看到消息: 您有 0 个朋友!

添加FriendsContextFriendsScreen

在此步骤中,您将设置应用程序来显示可能的朋友,并提供添加到当前的朋友的按钮。

接下来,打开FriendsScreen.js:

1nano FriendsScreen.js

并添加友情背景:

 1[label FriendsScreen.js]
 2import React from 'react';
 3import { StyleSheet, Text, View, Button } from 'react-native';
 4import { FriendsContext } from './FriendsContext';
 5
 6class FriendsScreen extends React.Component {
 7  // ...
 8}
 9FriendsScreen.contextType = FriendsContext;
10
11// ...

此代码建立一个Class.contextType

现在,创建一个按钮,在FriendsScreen.js中添加朋友:

 1[label FriendsScreen.js]
 2import React from 'react';
 3import { StyleSheet, Text, View, Button } from 'react-native';
 4import { FriendsContext } from './FriendsContext';
 5
 6class Friends extends React.Component {
 7  render() {
 8    return (
 9      <View style={styles.container}>
10        <Text>Add friends here!</Text>
11
12        {
13          this.context.possibleFriends.map((friend, index) => (
14            <Button
15              key={ friend }
16              title={ `Add ${ friend }` }
17              onPress={() =>
18                this.context.addFriend(index)
19              }
20            />
21          ))
22        }
23
24        <Button
25          title="Back to home"
26          onPress={() =>
27            this.props.navigation.navigate('Home')
28          }
29        />
30      </View>
31    );
32  }
33}
34FriendsScreen.contextType = FriendsContext;
35
36// ...

如果您在模拟器中重新打开应用程序并查看朋友屏幕,您将看到要添加的朋友列表。

HomeScreen with 0 currentFriends and FriendScreen with 3 possibleFriends

如果你访问朋友屏幕并点击添加朋友的按钮,你会看到可能的朋友列表下降。

您现在可以在屏幕之间导航,并在屏幕之间共享数据。

结论

在本教程中,您已经创建了一个 React Native 应用程序的样本,具有多个屏幕。 使用 React Navigation,您设计了一种在屏幕之间导航的方式。

完整的 本教程的源代码在GitHub上可用

如果您想更深入地挖掘 React 导航,请查看 他们的文档

React Navigation 不是唯一的路由和导航解决方案,还有 React Native Navigation, React Native Router FluxReact Router Native

如果您想了解更多关于 React 的信息,请查看我们的 如何在 React.js 中编码系列,或查看 我们的 React 主题页面以获取练习和编程项目。

Published At
Categories with 技术
Tagged with
comments powered by Disqus