React Native實(shí)現(xiàn)一個帶篩選功能的搜房列表(3)

原文鏈接React Native實(shí)現(xiàn)一個帶篩選功能的搜房列表(3)

在前兩篇文章中已經(jīng)介紹了如何實(shí)現(xiàn)一個支持下拉刷新和上拉加載更多的列表以及如何使用Redux進(jìn)行單向數(shù)據(jù)流,那這篇就會介紹下最后一個模塊篩選功能的開發(fā)即React Native與原生iOS的通信纵刘。

代碼傳送門--NNHybrid

關(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_PROPERTYRCT_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ù)雜的屬性。由于cityIdsubwayDataFilterMenuGeographicController這個子菜單才需要的翎苫,如果把它們設(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中。

參考:
Native Modules
Native UI Components

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末丑念,一起剝皮案震驚了整個濱河市涡戳,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌脯倚,老刑警劉巖渔彰,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異推正,居然都是意外死亡恍涂,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進(jìn)店門植榕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來再沧,“玉大人,你說我怎么就攤上這事尊残〕慈常” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵寝衫,是天一觀的道長顷扩。 經(jīng)常有香客問我,道長竞端,這世上最難降的妖魔是什么屎即? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮事富,結(jié)果婚禮上技俐,老公的妹妹穿的比我還像新娘。我一直安慰自己统台,他們只是感情好雕擂,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著贱勃,像睡著了一般井赌。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上贵扰,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天仇穗,我揣著相機(jī)與錄音,去河邊找鬼戚绕。 笑死纹坐,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的舞丛。 我是一名探鬼主播耘子,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼果漾,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了谷誓?” 一聲冷哼從身側(cè)響起绒障,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎捍歪,沒想到半個月后户辱,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡费封,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年焕妙,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片弓摘。...
    茶點(diǎn)故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡焚鹊,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出末患,到底是詐尸還是另有隱情,我是刑警寧澤锤窑,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站渊啰,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏绘证。R本人自食惡果不足惜隧膏,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望嚷那。 院中可真熱鬧,春花似錦魏宽、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蚌斩,卻和暖如春铆惑,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工鸭津, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留肠缨,地道東北人逆趋。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓晒奕,卻偏偏與公主長得像,于是被迫代替她去往敵國和親脑慧。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評論 2 355