参考文档:
官方文档
环境:
xcode 16.2
pod 1.16
ruby 3.0.0
安装依赖
必须安装的依赖有:Node、Watchman、Xcode 和 CocoaPods
Node & Watchman
我们推荐使用Homebrew来安装 Node 和 Watchman。在命令行中执行下列命令安装(如安装较慢可以尝试阿里云的镜像源):
brew install node@18brew install watchman
NPM还是需要安装一下,否则后面初始化还是不顺利
Yarn
Yarn是 Facebook 提供的替代 npm 的工具,可以加速 node 模块的下载。
npm install -g yarn
安装完 yarn 之后就可以用 yarn 代替 npm 了,例如用yarn
代替npm install
命令,用yarn add 某第三方库名
代替npm install 某第三方库名
。
准备工作
新建一个项目比如TestA ,初始化基本配置后,根目录下新建新建一个iOS文件夹,把原生相关的全部放在iOS目录里
cd 进入根目录 testA
2. 安装 NPM 依赖
进入根目录并运行以下命令:
curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.78-stable/template/package.json
这将从社区模板 复制 package.json
文件到您的项目中。
接下来,运行以下命令安装 NPM 包:
- Yarn
yarn install
安装过程创建了一个新的 node_modules
文件夹。该文件夹存储了构建项目所需的 JavaScript 依赖项。
将 node_modules/
添加到您的 .gitignore
文件中(社区默认文件)。
3. 默认已经安装好cocopods
4. 将 React Native 添加到您的应用
配置 CocoaPods
要配置 CocoaPods,我们需要两个文件:
- 一个 Gemfile 文件,定义了我们需要的 Ruby 依赖项。
- 一个 Podfile 文件,定义了如何正确安装我们的依赖项。
对于 Gemfile,请进入您的项目根目录并运行以下命令:
sh
curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.78-stable/template/Gemfile
这将下载 Gemfile 文件。 对于 Podfile,请进入您的项目 ios
文件夹并运行以下命令:
sh
curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.78-stable/template/ios/Podfile
请使用社区模板 作为 Gemfile 和 Podfile 的参考。
5. 编写 TypeScript 代码
现在我们将修改原生 iOS 应用程序以集成 React Native。
我们将编写的第一个代码片段是实际的 React Native 代码,该代码将集成到我们的应用程序中。
创建一个 index.js
文件
首先,在 React Native 项目的根目录中创建一个空的 index.js
文件。
index.js
是 React Native 应用程序的起点,并且总是需要。它可以是一个小文件,该文件 import
其他文件,这些文件是您的 React Native 组件或应用程序的一部分,或者它可以包含所有需要的代码。
我们的 index.js
文件应如下所示(社区模板文件 作为参考):
js
import {AppRegistry} from 'react-native';
import App from './App';
AppRegistry.registerComponent('HelloWorld', () => App);
这个地方不用改app名称
创建一个 App.tsx
文件
参考template即可
原生集成参考文档即可,可能需要开启vpn保证rn需要的库可以拉下来
6. 测试您的集成
您已经完成了将 React Native 与您的应用程序集成所需的所有基本步骤。现在我们将启动 Metro bundler 来构建您的 TypeScript 应用程序代码。Metro 的 HTTP 服务器从您的开发环境共享 bundle 到模拟器或设备。这允许 热重载。
首先,您需要在项目根目录中创建一个 metro.config.js
文件,如下所示:
js
const {getDefaultConfig} = require('@react-native/metro-config');module.exports = getDefaultConfig(__dirname);
您可以查看社区模板文件 作为参考。
Then, you need to create a .watchmanconfig
file in the root of your project. The file must contain an empty json object:
sh
echo {} > .watchmanconfig
一旦您有了配置文件,您可以运行 bundler。在项目根目录下运行以下命令:
- Yarn
yarn start
然后看到这个代表已经初步接入完毕
参考文档,修改props,原生与RN进行交互