本人是一个前端小小菜鸟,愿以此文献给跟我一样的人,大神请绕道而行,勿喷~
一、创建项目
安装依赖
1.通过npm电脑全局安装 react-native-cli
2.初始化项目 react-native init appName(appName:项目名称)
二、配置路由
安装依赖
1.yarn add react-navigation
2.yarn add react-native-gesture-handler
3.yarn add react-navigation-stack(4.0及以上版本需要安装此依赖)
react-navigation因版本不同,语法有些不一样
文献参考:https://reactnavigation.org/docs/en/stack-navigator.html
link依赖
react-native link react-native-gesture-handler
三、代码
1.首先在项目的根目录新建一个文件夹project
2.在新建的文件夹下再新建两个文件夹
(1)新建navigation文件夹,用于配置路由
(2)新建pages文件夹,用于存放页面
3.在navigation中新建index.js文件,书写配置路由,代码如下:
index.js
import { createStackNavigator } from 'react-navigation-stack';
import{ createAppContainer } from 'react-navigation';
import { Login, PhoneLogin} from '../pages/index';
const getOption = () =>({
header:null
})
const Router = createStackNavigator(
{
Login:{
screen:Login,
navigationOptions:getOption()
},
PhoneLogin:{
screen:PhoneLogin,
navigationOptions:getOption()
}
},
{
hearderBackTitleVisible:false
}
)
export default createAppContainer(Router)
4.在pages文件夹下新建三个文件
(1)Login.js (项目首页) 代码如下:
import React from "react";
import { StyleSheet, View, Text } from 'react-native';
export default class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
this.props.navigation.navigate('PhoneLogin')}>我可以跳转页面吗?
);
}
}
const styles = StyleSheet.create({
contaner: {
flex: 1,
justifyContent:'center',
alignItems: 'center',
},
content:{
width: 150,
height: 150,
justifyContent:'center',
alignItems: 'center',
backgroundColor: '#0f0',
}
});
(2)PhoneLogin.js(跳转后的页面) 代码如下:
import React from "react";
import {
Text,
StyleSheet,
StatusBar,
TouchableOpacity,
} from "react-native";
import { SafeAreaView } from "react-navigation";
export default class PhoneLogin extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
{this.props.navigation.navigate('Login')}} style={styles.test}>
我爱你,霞霞
);
}
}
const styles = StyleSheet.create({
contaner: {
backgroundColor: "#fff",
flex: 1,
justifyContent:'center',
alignItems: 'center',
},
test:{
width: 150,
height: 150,
justifyContent:'center',
alignItems: 'center',
backgroundColor: '#f00',
},
});
(3)index.js(页面汇总)代码如下:
import Login from './Login'
import PhoneLogin from './PhoneLogin'
export {
Login,
PhoneLogin,
}
(4)修改app.js文件 代码如下:
import React, { Component } from 'react'
import Router from './project/navigation/index'
export default class App extends Component {
render () {
console.disableYellowBox = true
return (
)
}
}
四、运行项目
确保真机与电脑连接且能正常使用
运行react-native run-android
作为小白的我,刚刚接触React-Native,路由配置百度了好久,终于找到一位大神写的文章,在那个基础上进行了修改,小小菜鸟,没怎么写过文章,望大佬们勿喷~