文档及模式的选择
具体过程需要阅读官方英文说明
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
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
vi ~/.zshrc
export PATH=$PATH:/opt/homebrew/bin
Node & Watchman
brew install npmbrew install nodebrew install watchmansudo 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…)。 转到位置面板并通过在命令行工具下拉列表中选择最新版本来安装工具。
VSCode
访问官方链接下载安装 VSCode https://code.visualstudio.com/docs
访问下面的链接安装 VSCode 的 React Native 插件
https://marketplace.visualstudio.com/items?itemName=msjsdiag.vscode-react-native
安装 ruby
brew install ruby
ls /opt/homebrew/Cellar/ruby
确认当前的版本号。然后
vi ~/.zshrc
export PATH=/opt/homebrew/Cellar/ruby/3.0.2_1/bin:$PATH:/opt/homebrew/binexport LDFLAGS="-L/opt/homebrew/Cellar/ruby/3.0.2_1/lib"export CPPFLAGS="-I/opt/homebrew/Cellar/ruby/3.0.2_1/include"
cocoapods
sudo gem install -n /usr/local/bin cocoapods
或
brew install cocoapods
yarn
npm install --global yarn
创建官方初试示例
# 使用nrm工具切换淘宝源# 如果之后需要切换回官方源可使用# npx nrm use npmnpx nrm use taobao
使用干净的梯子
npx react-native init FirstApp --template react-native-template-typescript
如果失败,根据提示,检查网络然后
cd ./FirstApp/ios && pod install
运行示例
Run instructions for Android:• Have an Android emulator running (quickest way to get started), or a device connected.• cd "/Users/david/ReactNative/Union" && npx react-native run-androidRun instructions for iOS:• cd "/Users/david/ReactNative/Union" && npx react-native run-ios- or -• Open Union/ios/Union.xcworkspace in Xcode or run "xed -b ios"• Hit the Run buttonRun instructions for macOS:• See https://aka.ms/ReactNativeGuideMacOS for the latest up-to-date instructions.
当前终端窗口
cd FirstAppnpx react-native start
另外打开一个新的终端窗口,进入 FirstApp 的目录
npx react-native run-ios

你也可以在Xcode中运行它。
清空应用代码
把 App.tsx 改成如下的内容
import React from 'react'import { View } from 'react-native';const App = () => {return (<View />);}export default App;
