文档及模式的选择

具体过程需要阅读官方英文说明
https://reactnative.dev/docs/environment-setup

如果阅读英文有困难,可以参考非官方中文翻译版
https://reactnative.cn/docs/environment-setup

不要去看其他任何书籍和网页的内容,大量过时或错误的内容。

我们使用 React Native CLI 的方式,而不使用 Expo CLI 。

不是试图去安装使用 create-react-app,这个已经过时了

安装基本工具

下面是 macOS 为开发环境,目标为 iOS 的环境

你将需要 Node、Watchman、React Native 命令行工具、XCode 和 CocoaPods。

虽然你可以选择任何编辑器来开发应用程序(我们选择 MS Visual Code),但你需要安装 Xcode 以设置必要的工具来构建适用于 iOS 的 React Native 应用程序。

HomeBrew

  1. /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
  1. vi ~/.zshrc
  1. export PATH=$PATH:/opt/homebrew/bin

Node & Watchman

  1. brew install npm
  2. brew install node
  3. brew install watchman
  4. sudo ln -s $(which node) /usr/local/bin/node

XCode

https://apps.apple.com/us/app/xcode/id497799835?mt=12
在安装 HomeBrew 的时候会自动安装 Xcode Command Line Tools。也可以按照下面的方法自己安装:

打开 Xcode,然后从 Xcode 菜单中选择“首选项…”(Preferences…)。 转到位置面板并通过在命令行工具下拉列表中选择最新版本来安装工具。
准备开发环境 - 图1

VSCode

访问官方链接下载安装 VSCode https://code.visualstudio.com/docs

访问下面的链接安装 VSCode 的 React Native 插件
https://marketplace.visualstudio.com/items?itemName=msjsdiag.vscode-react-native

安装 ruby

  1. brew install ruby
  1. ls /opt/homebrew/Cellar/ruby

确认当前的版本号。然后

  1. vi ~/.zshrc
  1. export PATH=/opt/homebrew/Cellar/ruby/3.0.2_1/bin:$PATH:/opt/homebrew/bin
  2. export LDFLAGS="-L/opt/homebrew/Cellar/ruby/3.0.2_1/lib"
  3. export CPPFLAGS="-I/opt/homebrew/Cellar/ruby/3.0.2_1/include"

cocoapods

  1. sudo gem install -n /usr/local/bin cocoapods

或

  1. brew install cocoapods

yarn

  1. npm install --global yarn

创建官方初试示例

  1. # 使用nrm工具切换淘宝源
  2. # 如果之后需要切换回官方源可使用
  3. # npx nrm use npm
  4. npx nrm use taobao

使用干净的梯子

  1. npx react-native init FirstApp --template react-native-template-typescript

如果失败,根据提示,检查网络然后

  1. cd ./FirstApp/ios && pod install

运行示例

  1. Run instructions for Android:
  2. • Have an Android emulator running (quickest way to get started), or a device connected.
  3. • cd "/Users/david/ReactNative/Union" && npx react-native run-android
  4. Run instructions for iOS:
  5. • cd "/Users/david/ReactNative/Union" && npx react-native run-ios
  6. - or -
  7. • Open Union/ios/Union.xcworkspace in Xcode or run "xed -b ios"
  8. • Hit the Run button
  9. Run instructions for macOS:
  10. • See https://aka.ms/ReactNativeGuideMacOS for the latest up-to-date instructions.

当前终端窗口

  1. cd FirstApp
  2. npx react-native start

另外打开一个新的终端窗口,进入 FirstApp 的目录

  1. npx react-native run-ios

image.png

你也可以在Xcode中运行它。


清空应用代码

把 App.tsx 改成如下的内容

  1. import React from 'react'
  2. import { View } from 'react-native';
  3. const App = () => {
  4. return (
  5. <View />
  6. );
  7. }
  8. export default App;