ReactNative进阶(一)页面导航

2020-02-17  本文已影响0人  维仔_411d

安装react-navigation组件、依赖、导航容器

yarn add @react-navigation/native
yarn add react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view
yarn add @react-navigation/stack

若react-native版本在0.60以下,还需要运行 react-native link
若在Mac电脑上,还需要cd ios; pod install; cd ..

引入react-native-gesture-handler

在项目入口文件最顶端,引入

// 将react-native-gesture-handler/index.js执行一遍,但不引入任何变量
import 'react-native-gesture-handler';

如果不做这一步,app可能在开发环境正常但是在生产环境会crash

用navigation组件包起整个app

import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
// createStackNavigator is a function that returns an object containing 2 properties: Screen and Navigator
const Stack = createStackNavigator();
function HomeScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
    </View>
  );
}
const App = ()=> {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};
export default function App() {
  return (
    <NavigationContainer>
      {/* Rest of your app code */}
    </NavigationContainer>
  );
}

Stack.Screen中的name属性的值Home为路由名称

定义多个路由

<NavigationContainer>
      <Stack.Navigator initialRouteName='Home'>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Login" component={LoginScreen} />
        <Stack.Screen name="Register" component={RegisterScreen} />
      </Stack.Navigator>
    </NavigationContainer>

定义多个路由,initialRouteName='Home'表示初始路由为Home;
tips:[1]

组件内跳转路由

export default LoginBtn extends component {
  _onPressButton = ()=> {
    this.props.navigation.navigate('DeviceList');
  };
  render() {
    return (
      <TouchableOpacity style={styles.loginSubmitBtn} onPress={this._onPressButton}>
         <Text style={styles.loginSumitEntry}>登录  </Text>
      </TouchableOpacity>
    );
  };
}

跳转到另一路由:this.props.navigation.navigate('目标路由');
跳转到与当前路由一致的路由:navigation.push('路由名');(若直接使用navigation.navigate('当前路由名')页面是没有任何动作的)
页面回退:navigation.back()
页面回退到堆栈中的第一个页面:navigation.poptotop()
tips:

向子组件传参

const HomeScreen = props => {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>
        {props.pro} Home {props.extraData}
      </Text>
    </View>
  );
};
<Stack.Screen name='Home'>
  {props => {
    return <HomeScreen pro={12} extraData={'A'} />;
  }}
</Stack.Screen>

navigate配置


  1. Hello React Navigation

上一篇下一篇

猜你喜欢

热点阅读