react-native 学习 - 环境搭建

260 阅读3分钟

为了适应业务发展,最近开始对 RN 相关知识进行技术积累, 今天来聊聊个人认为比较简单的 GettingStarted

搭建环境的两种方式

根据 RN 官网的 GettingStarted 指引, 搭建环境,有两种途径, expo goreact-native cli

环境搭建 - react-native cli

省流总结, 对web前端而言,属于地狱模式,需要安装 JDK, androidStudio, XCode, 每一步都是有坑要处理,问题状况千奇百怪。 我折腾完 JDK, android Studio 后 创建项目, 确实 对 android 方面没有积累,语法各种看不懂。折腾了半天,还是放弃了, 这里就不展示安装过程了。

环境搭建 - expo go

省流总结,只需要在 ios/ andoird 上安装 expo Go APP, 然后通过 create-expo-app 初始化项目, 跑启动命令 yarn start, 客户端上扫个码,就 o 了, 不需要在电脑上安装其他工具和环境了,十分方便。

简介

Expo 是一个基于 React Native 的开源工具集,可以帮助开发者更快速地构建 React Native 应用程序。它提供了一些预构建的组件和开发工具,使得开发者可以更加专注于应用程序的功能和用户体验,而不必担心构建和维护底层的基础架构。

IOS 安装

打开 App Store 应用 搜索 expo go 下载即可

image.png

下载完成后打开应用,在使用之前是需要进行登录操作的,这登录现在貌似是可以通了,之前老登录不进去。

image.png

这样 ios 环境 就准备好了

Android 安装

google play 可以直接下载, 如果没有或者特定品牌机型, 那也可以通过 APKPure 应用商店里面搜索

google play 内下载

image.png

APKPure 内下载

image.png

下载完成后,与 ios 一样,需要进行登录/注册操作

项目 quick start

环境准备好后,就可以开始初始化项目了, 这里默认你的机子上已经安装了 yarn, node16+

  1. 执行 yarn create expo-app 初始化项目
yarn create expo-app

creat-expo.gif

  1. 进入 app 目录,然后运行 yarn start
# 进入 app 目录
cd my-app
# 运行
yarn start

expo-start.gif

运行成功后,会看到一个 qrcode (貌似 只有 vscode 内置 terminate 有, git bash 没看到)

  1. 客户端扫码预览

安卓端,点击 appqrcode scan 按钮进行扫码预览

android-scan.gif

ios 端,打开 app 后, 使用系统自带的 qrcode 扫码功能进行扫码预览

ios-scan.gif

typescript 支持

如果希望项目使用 typescript 进行开发,只需要加个 tsconfig 配置即可, expo 本身就自带 ts 解析的

依赖安装

yarn add @types/react@18.0.24 @types/react-native typescript@4.9.4 --dev

tsconfig 配置

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react-native",
    "lib": ["es2017"],
    "types": ["react-native", "jest"],
    "skipLibCheck": true,
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"],
  "extends": "expo/tsconfig.base"
}

最后把 根目录的 App.jsx 改成 App.tsx 即可, 内容不需要调整

import { StatusBar } from 'expo-status-bar'
import { StyleSheet, Text, View } from 'react-native'

export default function App() {
  return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!!</Text>
      <StatusBar style='auto' />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center'
  }
})

参考资料