环境搭建
本次开发环境
node: v8.9.4
npm: 5.6.0
react: 16.0.0
react-native: 0.51.0
代码编辑器:webstorm
模拟器:ios => siMulator or 真机 / android => Android Studio自带模拟器 or 真机
- 安装Chocolatey,并使用Chocolatey安装python2和node.js
cmd下输入如下命令安装Chocolatey(或需翻墙)
@powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin
安装python2
choco install python2
安装node.js
choco install nodejs.install
设置npm镜像
npm config set registry https://registry.npm.taobao.org --global
npm config set disturl https://npm.taobao.org/dist --global
- Yarn、React Native的命令行工具
安装react-native脚手架
npm install -g yarn react-native-cli
配置yarn镜像
yarn config set registry https://registry.npm.taobao.org --global
yarn config set disturl https://npm.taobao.org/dist --global
- 安装Android SDK 并 配置ANDROID_HOME
- 创建并初始化项目,运行
react-native init projectDemo
cd projectDemo
react-native run-ios // ios启动
react-native run-android // android启动
最终生成项目目录
android: 安卓开发源码
ios: ios开发源码
node_modules: 项目依赖
.babelrc: babel的配置文件,将各种js版本的语言转换成运行环境所能识别的
App.js: react-native入口模板文件,供index.js使用,非固定
index.js: 项目入口文件
package.json 依赖配置文件
根据项目需求小做修改
可以看到我们为前端专门创建了一个项目文件src,并将 react-native入口模板文件迁移到项目文件夹里。根据项目需求分包
assets: 资源目录
imgs: 图片资源
styles: 样式资源
|—common.js: 公用样式资源
|—color.js: 定义项目颜色
|—layout.js: 定于项目布局
|—size.js: 定义项目尺寸
|—index.js: 整合以上资源
|—entry.js 对应页面路由样式资源
utils: 工具资源
|—api.js: 集成了整个项目的请求
|—http.js: 封装了fetch请求
|—screen.js: 有关屏幕的各种属性资源
|—system.js: 有关系统的各种资源
|—utils.js: 其他工具封装
components: 全局组件封装
pages: 页面
router: 路由
store: 全局状态管理
App.js: 入口模板文件
PS:编译错误一般会提示在node.js中,运行错误手机或模拟器弹出红色错误页面。修改js代码无需重装,点击红色错误页面的【RELOAD】即可或摇动手机弹出开发菜单【RELOAD】
组件 控件
RN中每个页面都是由【Component 】组成,也可用【Component 】来做组合控件
基本组件代码
//引入React Component
import React, {Component} from 'react'
//引入控件
import {
View,
Text,
} from 'react-native'
//变量的定义只能放Component不可放Component里面,否则调用报错。函数可以放Component里面
let val = 1;
//export default 才可以把这个组件暴露出去,否则其他文件调用会报错(提示找不到Demo组件或者找到的Demo组件不是Component)
export default class Demo extends Component {
//构造函数,props作为父子控件直接传递数据,后面讲
constructor(props) {
super(props)
}
//渲染 最终的UI效果在此
render() {
return (
<View>
<Text style={
{marginTop: 20, fontSize: 16}}>react-native通用基础模板</Text>
<View>
{
/*<Text>{listStore.num}</Text>*/}
</View>
</View>
)
}
}
常用控件
Text Button Image TextInput ScrollView ListView ,具体控件和属性、方法参考 React Native 中文网文档
布局 与 导航
布局 在控件的style中直接设置,共有5种属性,可搭配使用(正常是Flex Direction确认主轴后搭配其他)
<View style={
{
flex: 1, flexDirection: 'row'}}>