Simple example of React Native calling Objective-C

React Native 调用Objective-C

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

 

In Xcode, File->New->File->Cocoa Class-> (Class:'SomeString', Subclass Of:'NSObject', Language:'Objective-C')->save as project name/ios/project name . At this time, SomeString.h and SomeString.m files will be generated.

 

Modify the contents of these two files to:

//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

 

Modify index.ios.js

The following is a reference file, the project name is Test1, the purpose is to call Objective-C and return a string

----

'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);

---

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327057559&siteId=291194637