React-Native集成到已有项目过程及问题处理

本文详述了将React-Native集成到已有的iOS项目中的步骤,包括安装依赖、配置React Native框架、代码集成、RCTRootView使用、测试集成效果,以及解决App Transport Security和运行报错的问题。在集成过程中,需确保安装了必要的工具,并正确配置Podfile,创建React Native组件,并处理ATS设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看搞清楚项目目录情况:

项目目录

第一层目录:项目根目录: iOS-2028-master/
第二层目录:原生项目根目录:iOS-2048-master/NumberTileGame/

另外假设已经全局安装好node、npm、cocoapods、react-native cli等工具,这些工具没有安装的,请先自行Google安装。

Packages Installation

  1. 进入项目根目录 iOS-2028-master/,新建package.json文件,在文件里输入如下内容:
{
  "name": "NumberTileGame",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "dependencies": {
    "react": "15.0.2",
    "react-native": "0.26.1"
  }
}
  1. 在当前根目录 iOS-2028-master/ 下执行
$ npm install

React Native Framework

  1. 进入到原生项目根目录,通过pod 引入React Native Framework, 执行如下操作:
## In the directory where your native iOS code is located (e.g., where your `.xcodeproj` file is located)

$ pod init
  1. 在创建好的Podfile中输入如下内容:
# The target name is most likely the name of your project.
target 'NumberTileGame' do

  # Your 'node_modules' directory is probably in the root of your project,
  # but if not, adjust the `:path` accordingly
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'RCTText',
    'RCTWebSocket', # needed for debugging
    # Add any other subspecs you want to use in your project
  ]
  end
  1. 执行Pod安装
$ pod install

如果出现如下代码,表示安装正常

Analyzing dependencies
Fetching podspec for `React` from `../node_modules/react-native`
Downloading dependencies
Installing React (0.26.0)
Generating Pods project
Integrating client project
Sending stats
Pod installation complete! There are 3 dependencies from the Podfile and 1 total pod installed.

代码集成

The React Native component
  1. 进入项目根目录 iOS-2048-master/ ,创建index.ios.js文件
# In root of your project
$ touch index.ios.js
  1. 在该文件中引入你要加入的react native code, 参考代码如下:
'use strict';

import React from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class RNHighScores extends React.Component {
  render() {
    var contents = this.props["scores"].map(
      score => <Text key={score.name}>{score.name}:{score.value}{"\n"}</Text>
    );
    return (
      <View style={styles.container}>
        <Text style={styles.highScoresTitle}>
          2048 High Scores!
        </Text>
        <Text style={styles.scores}>
          {contents}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  highScoresTitle: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  scores: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// Module name
AppRegistry.registerComponent('RNHighScores', () => RNHighScores);

RNHighScores is the name of your module that will be used when you add
a view to React Native from within your iOS application.

The Magic: RCTRootView

在 ViewController上面添加按键High Scores,同时添加点击事件:
这里写图片描述

然后再在ViewController里加入如下代码:

#import "RCTRootView.h"
- (IBAction)highScoreButtonPressed:(id)sender {
    NSLog(@"High Score Button Pressed");
    NSURL *jsCodeLocation = [NSURL
                             URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];
    RCTRootView *rootView =
      [[RCTRootView alloc] initWithBundleURL : jsCodeLocation
                           moduleName        : @"RNHighScores"
                           initialProperties :
                             @{
                               @"scores" : @[
                                 @{
                                   @"name" : @"Alex",
                                   @"value": @"42"
                                  },
                                 @{
                                   @"name" : @"Joel",
                                   @"value": @"10"
                                 }
                               ]
                             }
                           launchOptions    : nil];
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;
    [self presentViewController:vc animated:YES completion:nil];
}

Test Your Integration

App Transport Security

info.plist文件里加入:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>
Run the Packager
# From the root of your project, where the `node_modules` directory is located.
$ npm start
Run the App
# From the root of your project
$ react-native run-ios

这里写图片描述

这里写图片描述

编译Xcode项目时,如果出现如下错误:
编译报错如下:

Undefined symbols for architecture x86_64:
"std::terminate()", referenced from:
___clang_call_terminate in libReact.a(RCTJSCExecutor.o)
"___cxa_begin_catch", referenced from:
___clang_call_terminate in libReact.a(RCTJSCExecutor.o)
"___gxx_personality_v0", referenced from:
-[RCTJavaScriptContext initWithJSContext:onThread:] in libReact.a(RCTJSCExecutor.o)
-[RCTJavaScriptContext init] in libReact.a(RCTJSCExecutor.o)
-[RCTJavaScriptContext invalidate] in libReact.a(RCTJSCExecutor.o)
_RCTNSErrorFromJSError in libReact.a(RCTJSCExecutor.o)
+[RCTJSCExecutor runRunLoopThread] in libReact.a(RCTJSCExecutor.o)
-[RCTJSCExecutor init] in libReact.a(RCTJSCExecutor.o)
-[RCTJSCExecutor context] in libReact.a(RCTJSCExecutor.o)
...
ld: symbol(s) not found for architecture x86_64

解决办法:

在Other Linker Flags中添加-lc++即可。
注:-lc++要添加在JavaScriptCore之后,否则编译也不过。

编程成功,进入点击High Scores 进入React Native页面报错,请开启本地服务器:
进入项目根目录 iOS-2048-master/ , 执行如下操作:

$  npm start

有其他各种常见问题,欢迎加我QQ1684484321讨论。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值