原文鏈接React Native實(shí)現(xiàn)一個帶篩選功能的搜房列表(3)
在前兩篇文章中已經(jīng)介紹了如何實(shí)現(xiàn)一個支持下拉刷新和上拉加載更多的列表以及如何使用Redux進(jìn)行單向數(shù)據(jù)流,那這篇就會介紹下最后一個模塊篩選功能的開發(fā)即React Native與原生iOS的通信纵刘。
關(guān)于如何進(jìn)行React Native與原生iOS的通信式塌,在官網(wǎng)中有很明確的教程褥影,這里我就不細(xì)說了双揪。我分享的主要是如何利用那些接口實(shí)現(xiàn)這樣的一個效果视事。
在項(xiàng)目中强重,篩選條和對應(yīng)的子菜單都是使用原生代碼實(shí)現(xiàn)的监憎,而列表使用js代碼實(shí)現(xiàn)的纱意。我們要做的就是將這些原生頁面通過橋接的方式添加到j(luò)s頁面上。
橋接實(shí)現(xiàn)在FHTFilterMenuManager
這個類中鲸阔,其實(shí)現(xiàn)如下:
- 原生實(shí)現(xiàn)
// .h
#import <React/RCTViewManager.h>
#import "FHTFilterMenu.h"
@interface FHTFilterMenu (RNBridge)
@property (nonatomic, copy) RCTBubblingEventBlock onUpdateParameters;
@property (nonatomic, copy) RCTBubblingEventBlock onChangeParameters;
@end
@interface RCTConvert (FHTFilterMenu)
@end
@interface FHTFilterMenuManager : RCTViewManager <RCTBridgeModule>
@end
// .m
#import "FHTFilterMenuManager.h"
#import <React/RCTUIManager.h>
#import <objc/runtime.h>
#import "FilterMenuRentTypeController.h"
#import "FilterMenuGeographicController.h"
#import "FilterMenuOrderByController.h"
#import "FilterMenuMoreController.h"
#import "FilterMenuRentalController.h"
static ConstString kFilterParams = @"filterParams";
typedef NS_ENUM(NSInteger, FilterMenuType) {
FilterMenuTypeNone,
FilterMenuTypeEntireRent, //整租
FilterMenuTypeSharedRent, //合租
FilterMenuTypeApartment, //獨(dú)棟公寓
FilterMenuTypeBelowThousand, //千元房源
FilterMenuTypePayMonthly, //月付
FilterMenuTypeVR, //VR
};
@implementation RCTConvert (FHTFilterMenu)
RCT_ENUM_CONVERTER(FilterMenuType,
(@{@"None": @(FilterMenuTypeNone),
@"EntireRent": @(FilterMenuTypeEntireRent),
@"SharedRent": @(FilterMenuTypeSharedRent),
@"Apartment": @(FilterMenuTypeApartment),
@"BelowThousand": @(FilterMenuTypeBelowThousand),
@"PayMonthly": @(FilterMenuTypePayMonthly),
@"VR":@(FilterMenuTypeVR)}),
FilterMenuTypeNone,
integerValue);
@end
@implementation FHTFilterMenu (RNBridge)
#pragma mark - Setter & Getter
- (void)setOnUpdateParameters:(RCTBubblingEventBlock)onUpdateParameters {
objc_setAssociatedObject(self,
@selector(onUpdateParameters),
onUpdateParameters,
OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (RCTBubblingEventBlock)onUpdateParameters {
return objc_getAssociatedObject(self, @selector(onUpdateParameters));
}
- (void)setOnChangeParameters:(RCTBubblingEventBlock)onChangeParameters {
objc_setAssociatedObject(self,
@selector(onChangeParameters),
onChangeParameters,
OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (RCTBubblingEventBlock)onChangeParameters {
return objc_getAssociatedObject(self, @selector(onChangeParameters));
}
- (void)setFilterMenuType:(FilterMenuType)filterMenuType {
switch (filterMenuType) {
case FilterMenuTypeEntireRent: {
UIViewController *vc = (UIViewController *)self.filterControllers[0];
[vc presetWithOptionTitles:@[@"整租"]];
}
break;
case FilterMenuTypeSharedRent: {
UIViewController *vc = (UIViewController *)self.filterControllers[0];
[vc presetWithOptionTitles:@[@"合租"]];
}
break;
case FilterMenuTypeApartment: {
UIViewController *vc = (UIViewController *)self.filterControllers[3];
[vc presetWithOptionTitles:@[@"房源類型/獨(dú)棟公寓"]];
}
break;
case FilterMenuTypeBelowThousand: {
UIViewController *vc = (UIViewController *)self.filterControllers[2];
[vc presetWithOptionTitles:@[@"1500以下"]];
}
break;
case FilterMenuTypePayMonthly: {
UIViewController *vc = (UIViewController *)self.filterControllers[3];
[vc presetWithOptionTitles:@[@"房源亮點(diǎn)/月付"]];
}
break;
case FilterMenuTypeVR: {
UIViewController *vc = (UIViewController *)self.filterControllers[3];
[vc presetWithOptionTitles:@[@"房源亮點(diǎn)/VR"]];
}
break;
default:
break;
}
};
@end
@implementation FHTFilterMenuManager
RCT_EXPORT_MODULE();
RCT_EXPORT_VIEW_PROPERTY(onUpdateParameters, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onChangeParameters, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(filterMenuType, FilterMenuType);
RCT_CUSTOM_VIEW_PROPERTY(cityId, NSString, FHTFilterMenu) {
FilterMenuGeographicController *vc = view.filterControllers[1];
vc.cityId = (NSString *)json;
};
RCT_CUSTOM_VIEW_PROPERTY(subwayData, NSArray, FHTFilterMenu) {
FilterMenuGeographicController *vc = view.filterControllers[1];
vc.originalSubwayData = (NSArray *)json;
};
RCT_EXPORT_METHOD(showFilterMenuOnView:(nonnull NSNumber *)containerTag filterMenuTag:(nonnull NSNumber *)filterMenuTag) {
RCTUIManager *uiManager = self.bridge.uiManager;
dispatch_async(uiManager.methodQueue, ^{
[uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *,UIView *> *viewRegistry) {
UIView *view = viewRegistry[containerTag];
FHTFilterMenu *filterMenu = (FHTFilterMenu *)viewRegistry[filterMenuTag];
[filterMenu showFilterMenuOnView:view];
}];
});
}
- (dispatch_queue_t)methodQueue {
return dispatch_get_main_queue();
}
- (UIView *)view {
FilterMenuRentTypeController *rentTypeVC =
[[FilterMenuRentTypeController alloc] initWithStyle:UITableViewStylePlain];
FilterMenuGeographicController *geographicVC = [FilterMenuGeographicController new];
FilterMenuRentalController *rentalVC =
[[FilterMenuRentalController alloc] initWithStyle:UITableViewStylePlain];
FilterMenuMoreController *moreVC = [FilterMenuMoreController new];
FilterMenuOrderByController *orderByVC =
[[FilterMenuOrderByController alloc] initWithStyle:UITableViewStylePlain];
CGRect frame = CGRectMake(0, FULL_NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, 44);
FHTFilterMenu *filterMenu = [[FHTFilterMenu alloc] initWithFrame:frame];
filterMenu.filterControllers = @[rentTypeVC, geographicVC, rentalVC, moreVC, orderByVC];
[filterMenu dismissSubmenu:NO];
[filterMenu resetFilter];
[rentTypeVC presetWithOptionTitles:@[]];
__weak FHTFilterMenu *weakFilterMenu = filterMenu;
rentTypeVC.didSetFilterHandler = ^(NSDictionary * _Nonnull params) {
BLOCK_EXEC(weakFilterMenu.onUpdateParameters, @{kFilterParams: params});
};
geographicVC.didSetFilterHandler = ^(NSDictionary * _Nonnull params) {
NSMutableDictionary *tmpParams = [@{@"regionId": nn_makeSureString(params[@"regionId"]),
@"zoneIds": nn_makeSureArray(params[@"zoneIds"]),
@"subwayRouteId": nn_makeSureString(params[@"subwayRouteId"]),
@"subwayStationCodes": nn_makeSureArray(params[@"subwayStationCodes"])} mutableCopy];
BLOCK_EXEC(weakFilterMenu.onUpdateParameters, @{kFilterParams: [tmpParams copy]});
};
rentalVC.didSetFilterHandler = ^(NSDictionary * _Nonnull params) {
NSDictionary *tmpParams = @{@"minPrice": nn_makeSureString(params[@"minPrice"]),
@"maxPrice": nn_makeSureString(params[@"maxPrice"])};
BLOCK_EXEC(weakFilterMenu.onUpdateParameters, @{kFilterParams: tmpParams});
};
moreVC.didSetFilterHandler = ^(NSDictionary * _Nonnull params) {
NSArray *typeArray = params[@"typeArray"];
NSString *type = typeArray.count == 1 ? (typeArray.lastObject)[@"type"] : @"";
NSDictionary *tmpParams = @{@"roomAttributeTags": params[@"highlightArray"],
@"chamberCounts": params[@"chamberArray"],
@"type": type};
BLOCK_EXEC(weakFilterMenu.onUpdateParameters, @{kFilterParams: tmpParams});
};
orderByVC.didSetFilterHandler = ^(NSDictionary * _Nonnull params) {
BLOCK_EXEC(weakFilterMenu.onUpdateParameters, @{kFilterParams: params});
};
filterMenu.filterDidChangedHandler = ^(FHTFilterMenu * _Nonnull filterMenu, id<FHTFilterController> _Nonnull filterController) {
BLOCK_EXEC(weakFilterMenu.onChangeParameters, nil);
};
return filterMenu;
}
@end
- JS實(shí)現(xiàn)
import React, { Component } from 'react';
import { requireNativeComponent, NativeModules, findNodeHandle } from 'react-native';
const FilterMenu = requireNativeComponent('FHTFilterMenu', SearchFilterMenu);
const filterMenuManager = NativeModules.FHTFilterMenuManager;
export const FilterMenuType = {
NONE: 'None',
ENTIRERENT: 'EntireRent',
SHAREDRENT: 'SharedRent',
APARTMENT: 'Apartment',
BELOWTHOUSAND: 'BelowThousand',
PAYMONTHLY: 'PayMonthly',
VR: 'VR'
}
export default class SearchFilterMenu extends Component {
componentDidUpdate() {
const filterMenuTag = findNodeHandle(this.refs.filterMenu);
const containerTag = findNodeHandle(this.props.containerRef);
if (filterMenuTag && containerTag) filterMenuManager.showFilterMenuOnView(containerTag, filterMenuTag);
}
render() {
return <FilterMenu ref='filterMenu' {...this.props} />;
}
}
- JS調(diào)用
<SearchFilterMenu
style={styles.filterMenu}
cityId={`${home.cityId}`}
subwayData={home.subwayData}
containerRef={this.refs.container}
filterMenuType={this.params.filterMenuType}
onChangeParameters={() => this._loadData(true)}
onUpdateParameters={({ nativeEvent: { filterParams } }) => {
this.filterParams = {
...this.filterParams,
...filterParams,
};
}}
/>
創(chuàng)建ViewManager
FHTFilterMenuManager
是繼承自RCTViewManager
偷霉,每一個原生UI都需要被一個RCTViewManager
的子類來創(chuàng)建和管理迄委。在程序運(yùn)行過程中,RCTViewManager
會創(chuàng)建原生UI并把視圖提供給RCTUIManager
腾它,RCTUIManager
則反過來委托RCTViewManager
在需要的時候去設(shè)置和更新視圖的屬性跑筝。這里有一個注意點(diǎn):ViewManager的命名格式是原生組件名字+Manager。
在ViewManager中最重要的是必須實(shí)現(xiàn)- (UIView *)view
瞒滴,用來返回你想要橋接的原生UI曲梗。
從React Native傳遞屬性到原生組件
我們知道屬性是最簡單的跨組件通信,如果RN組件接受到一個屬性的時候妓忍,可以通過RCT_EXPORT_VIEW_PROPERTY
和RCT_CUSTOM_VIEW_PROPERTY
的方式傳遞給原生組件虏两。
RCT_EXPORT_VIEW_PROPERTY
可以將原生組件自帶的屬性暴露給JS。所以在FHTFilterMenuManager
中世剖,我暴露三個自帶的屬性給JS定罢,分別是
// 點(diǎn)擊確定按鈕執(zhí)行網(wǎng)絡(luò)請求的block
RCT_EXPORT_VIEW_PROPERTY(onUpdateParameters, RCTBubblingEventBlock);
// 點(diǎn)擊子菜單item,參數(shù)變更的block
RCT_EXPORT_VIEW_PROPERTY(onChangeParameters, RCTBubblingEventBlock);
// 篩選菜單的類型旁瘫,
RCT_EXPORT_VIEW_PROPERTY(filterMenuType, FilterMenuType);
這里我使用了分類的方式對原生組件的屬性進(jìn)行拓展祖凫,因?yàn)樵陧?xiàng)目中,我并不希望原生組件有太多RN橋接相關(guān)的代碼酬凳,所以使用分類拓展惠况,這樣也可以對代碼進(jìn)行解耦。
這里有一個注意點(diǎn):如果自帶的屬性是block類型的話宁仔,屬性名必須以on開頭稠屠。
RCT_CUSTOM_VIEW_PROPERTY
可以讓我們添加一些更為復(fù)雜的屬性。由于cityId
和subwayData
是FilterMenuGeographicController
這個子菜單才需要的翎苫,如果把它們設(shè)置為FHTFilterMenu
的屬性并不合適权埠,而FilterMenuGeographicController
我們并沒有暴露給JS,所以我們可以使用RCT_CUSTOM_VIEW_PROPERTY
對沒有暴露給JS的對象進(jìn)行屬性傳遞煎谍。
RCT_CUSTOM_VIEW_PROPERTY(cityId, NSString, FHTFilterMenu) {
FilterMenuGeographicController *vc = view.filterControllers[1];
vc.cityId = (NSString *)json;
};
RCT_CUSTOM_VIEW_PROPERTY(subwayData, NSArray, FHTFilterMenu) {
FilterMenuGeographicController *vc = view.filterControllers[1];
vc.originalSubwayData = (NSArray *)json;
};
React Native調(diào)用原生組件的方法
RCT_EXPORT_METHOD
用來提供原生方法給JS調(diào)用攘蔽。RCT_EXPORT_METHOD(showFilterMenuOnView:(nonnull NSNumber *)containerTag filterMenuTag:(nonnull NSNumber *)filterMenuTag)
用來實(shí)現(xiàn)將子菜單添加到SearchHousePage
,其實(shí)現(xiàn)如下:
RCT_EXPORT_METHOD(showFilterMenuOnView:(nonnull NSNumber *)containerTag filterMenuTag:(nonnull NSNumber *)filterMenuTag) {
RCTUIManager *uiManager = self.bridge.uiManager;
dispatch_async(uiManager.methodQueue, ^{
[uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *,UIView *> *viewRegistry) {
UIView *view = viewRegistry[containerTag];
FHTFilterMenu *filterMenu = (FHTFilterMenu *)viewRegistry[filterMenuTag];
[filterMenu showFilterMenuOnView:view];
}];
});
}
其中containerTag
代碼用來表示SearchHousePage
呐粘,filterMenuTag
則表示篩選條秩彤。這里有一個注意點(diǎn):不能使用self.view的方式因?yàn)闀?chuàng)建出一個新的FHTFilterMenu對象,更不能在- (UIView *)view
中使用一個指針對創(chuàng)建出來的View進(jìn)行引用事哭,如果你的組件在多個頁面都用使用的話,是會出問題的瓜富。
另外鳍咱,由于iOS的UI操作是要放在主線程完成的,所以最好methodQueue
指定為主線程与柑。
結(jié)尾
到這里整個SearchHousePage
頁面的開發(fā)已經(jīng)完成谤辜,如果需要查看完整代碼的話蓄坏,在代碼傳送門--NNHybrid中。