---
title: "React Native 调用Objective-C简单例子"
author: "ipython"
date: "2016-01-27T23:01:20Z"
tags: []
categories: ["移动开发"]
slug: "react-native-objective-c"
draft: false
lastmod: "2016-01-27T23:01:20Z"
id: 2274429
url: "https://ipython.iteye.com/blog/2274429"
---

React Native 调用Objective-C

参考：https://colinramsay.co.uk/2015/03/27/react-native-simple-native-module.html

 

在Xcode中，File-&gt;New-&gt;File-&gt;Cocoa Class-&gt; (Class:'SomeString',  Subclass Of:'NSObject', Language:'Objective-C')-&gt;保存为 项目名/ios/项目名。 这时会生成SomeString.h和SomeString.m文件。

 

修改这两个文件的内容为:

//SomeString.h

#import "RCTBridgeModule.h"

@interface SomeString : NSObject&lt;RCTBridgeModule&gt;

@end

 

//SomeString.m

#import "SomeString.h"

@implementation SomeString

RCT\_EXPORT\_MODULE();

RCT\_EXPORT\_METHOD(get:(RCTResponseSenderBlock)callback)

{

  NSString* someString = @"something, this is from Objective C";

  callback(@\[someString]);

}

@end

 

修改index.ios.js

以下是一个参考文件，项目名为Test1,目的是调用Objective-C，返回一个字符串

\----

'use strict';

import React, {

  AppRegistry,

  Component,

  StyleSheet,

  Text,

  View,

  NativeModules,

} from 'react-native';

 

class Test1 extends Component {

  constructor(props){

      super(props);

      this.state = {

          text: 'hello',

      };

  }

 

  componentDidMount() {

    var ss = NativeModules.SomeString.get(x=&gt;this.setState({text:x}));

  }

 

  render () {

    return (

      &lt;View style={styles.container} &gt;

        &lt;Text&gt;{this.state.text}&lt;/Text&gt;

      &lt;/View&gt;

    );

  }

 

}

 

const styles = StyleSheet.create({

  container: {

    flex: 1,

    justifyContent: 'center',

    alignItems: 'center',

    backgroundColor: '#F5FCFF',

  },

});

 

AppRegistry.registerComponent('Test1', () =&gt; Test1);

\---