创建React-native部件
1、创建项目:react-native init MessageBox本文的目标是建立一个信息提示窗,在ios下使用UIAlertController,而在Android下则使用Toast。项目比较简单,主要是为了展示创建自定义部件的方法。
2、创建一个Cocoa Touch class:ZHMessageBox,它继承了NSObject类

3、修改ZHMessageBox.h,使其遵循RCTBridgeModule协议:#import "RCTBridge.h"@interface ZHMessageBox : NSObject <RCTBridgeModule>@end
4、Objective-C的实现:@interface ZHMessageBox () @propert烤恤鹇灭y (nonatomic, strong) UIAlertController* alert; @property (nonatomic, strong) NSTimer* timer;@end@implementation ZHMessageBox // Expose this module to the React Native bridge RCT_EXPORT_MODULE() RCT_EXPORT_METHOD(show:(NSString *)title message:(NSString *)message) { self.alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert]; UIViewController* vc = [[[UIApplication sharedApplication]delegate]window].rootViewController; [vc presentViewController:self.alert animated:YES completion:^{ self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(onTimeOff:) userInfo:nil repeats:NO]; }]; } -(void)onTimeOff:(NSTimer*)timer { [self.alert dismissViewControllerAnimated:YES completion:^{ self.alert = nil; }]; [self.timer invalidate]; self.timer = nil; }@end
5、Javascript中调用:import {ZHMes衡痕贤伎sageBox} from 'NativeModules';class MessageBox extends Component { render() { return ( <View style={styles.container}> <TouchableHighlight onPress={this._onPressButton}> <Text> Show alert </Text> </TouchableHighlight> </View> ); } _onPressButton() { ZHMessageBox.showAlert( 'Alert', 'My message' ) }}
6、运行。
