React Native 调用Objective-C简单例子

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:44   1936   0

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

---

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP