React-Native JS 加载原生组件(iOS)
2019-02-13 本文已影响18人
精神病患者link常
举例:在
RN
中,使用image
加载网络图片,但是RN
的image
是没有缓存效果的;原生中, 使用的是SDWebImage
进行图片的缓存处理。如何让RN
中也有图片缓存效果呢~
直接让RN加载原生组件就可以啦
一:一个简单的JS 加载原生组件
先简单的熟悉下JS是怎么实现加载原生组件的
1. 首先我们需要requireNativeComponent
这个东东帮助我们在JS中获取原生组件
import {
requireNativeComponent
} from 'react-native';
var NativeView = requireNativeComponent('NativeViewClass');
2. 这是 NativeView
就是获取到的原生组件;NativeViewClass
就是原生组件的类名。我们可以直接使用NativeView
进行布局~
<NativeView style={{width: 100, height:100}} />
3. 看下原生NativeViewClass
是怎么实现的
NativeView.h
#import <React/RCTViewManager.h>
@interface NativeView : RCTViewManager
@end
NativeView.m
#import "NativeView.h"
@implementation NativeView
RCT_EXPORT_MODULE() // 默认导出 NativeView
// 需要实现该方法,目的是返回组件,在RN中获取到的组件就是view
- (UIView *)view
{
UILabel *view = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
view.backgroundColor = [UIColor redColor];
return view;
}
@end
4. OK~一个简单的JS 加载原生组件就搞定啦~, 看下效果~

5. 现在我想在label上显示一个文字,该怎么显示呢~ 这时候就需要
RCT_EXPORT_VIEW_PROPERTY
出马啦,专门导出属性使用滴~
#import "NativeView.h"
@implementation NativeView
RCT_EXPORT_MODULE()
- (UIView *)view
{
UILabel *view = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
view.backgroundColor = [UIColor redColor];
return view;
}
RCT_EXPORT_VIEW_PROPERTY(text, NSString)
@end
RN中使用~
<NativeView style={{width: 100, height:100, marginTop: 100}}
text={'哈哈'}
/>
效果~

6. 假如我在导出一个属性 placeholder
~
RCT_EXPORT_VIEW_PROPERTY(placeholder, NSString)
<NativeView style={{width: 100, height:100, marginTop: 100}}
text={'哈哈'}
placeholder={'啦啦啦'}
/>

7. 通过对比这个错误和设置text,可以这样的猜测~
在RN中使用的NativeView 就是 原生的UILabel对象
NativeView设置属性就是给UILabel对象的属性并实现set方法
UILabel 有text属性,可以实现set方法,但是没有placeholder 属性所以不能实现set方法,所以报错

8. 我想加一个点击事件~
为了规范及复用情况,我把类整理一下
原生


RN


二:一个完整的加载原生视图
将以上代码修改修改~
原生


RN

使用

