React Native 调用Objective-C简单例子

80530297 2016-01-27

React Native 调用Objective-C

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

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

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

//SomeString.h

#import "RCTBridgeModule.h"

@interface SomeString : NSObject<RCTBridgeModule>

@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=>this.setState({text:x}));

  }

  render () {

    return (

      <View style={styles.container} >

        <Text>{this.state.text}</Text>

      </View>

    );

  }

}

const styles = StyleSheet.create({

  container: {

    flex: 1,

    justifyContent: 'center',

    alignItems: 'center',

    backgroundColor: '#F5FCFF',

  },

});

AppRegistry.registerComponent('Test1', () => Test1);

---

相关推荐