React Native實現一個帶篩選功能的搜房列表(3)

原文連接React Native實現一個帶篩選功能的搜房列表(3)react

在前兩篇文章中已經介紹瞭如何實現一個支持下拉刷新和上拉加載更多的列表以及如何使用Redux進行單向數據流,那這篇就會介紹下最後一個模塊篩選功能的開發即React Native與原生iOS的通訊。ios

開始以前,仍是先看一下最終實現的效果 git

search_house

代碼傳送門--NNHybridgithub

關於如何進行React Native與原生iOS的通訊,在官網中有很明確的教程,這裏我就不細說了。我分享的主要是如何利用那些接口實現這樣的一個效果。json

在項目中,篩選條和對應的子菜單都是使用原生代碼實現的,而列表使用js代碼實現的。咱們要作的就是將這些原生頁面經過橋接的方式添加到js頁面上。react-native

橋接實如今FHTFilterMenuManager這個類中,其實現以下:bash

  • 原生實現
// .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,     //獨棟公寓
    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:@[@"房源類型/獨棟公寓"]];
        }
            break;
        case FilterMenuTypeBelowThousand: {
            UIViewController *vc = (UIViewController *)self.filterControllers[2];
            [vc presetWithOptionTitles:@[@"1500如下"]];
        }
            break;
        case FilterMenuTypePayMonthly: {
            UIViewController *vc = (UIViewController *)self.filterControllers[3];
            [vc presetWithOptionTitles:@[@"房源亮點/月付"]];
        }
            break;
        case FilterMenuTypeVR: {
            UIViewController *vc = (UIViewController *)self.filterControllers[3];
            [vc presetWithOptionTitles:@[@"房源亮點/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實現
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調用
<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,
        };
    }}
/>
複製代碼

建立ViewManager

FHTFilterMenuManager是繼承自RCTViewManager,每個原生UI都須要被一個RCTViewManager的子類來建立和管理。在程序運行過程當中,RCTViewManager會建立原生UI並把視圖提供給RCTUIManagerRCTUIManager則反過來委託RCTViewManager在須要的時候去設置和更新視圖的屬性。這裏有一個注意點:ViewManager的命名格式是原生組件名字+Manager網絡

在ViewManager中最重要的是必須實現- (UIView *)view,用來返回你想要橋接的原生UI。async

從React Native傳遞屬性到原生組件

咱們知道屬性是最簡單的跨組件通訊,若是RN組件接受到一個屬性的時候,能夠經過RCT_EXPORT_VIEW_PROPERTYRCT_CUSTOM_VIEW_PROPERTY的方式傳遞給原生組件。ui

RCT_EXPORT_VIEW_PROPERTY能夠將原生組件自帶的屬性暴露給JS。因此在FHTFilterMenuManager中,我暴露三個自帶的屬性給JS,分別是

// 點擊肯定按鈕執行網絡請求的block
RCT_EXPORT_VIEW_PROPERTY(onUpdateParameters, RCTBubblingEventBlock);
// 點擊子菜單item,參數變動的block
RCT_EXPORT_VIEW_PROPERTY(onChangeParameters, RCTBubblingEventBlock);
// 篩選菜單的類型,
RCT_EXPORT_VIEW_PROPERTY(filterMenuType, FilterMenuType);
複製代碼

這裏我使用了分類的方式對原生組件的屬性進行拓展,由於在項目中,我並不但願原生組件有太多RN橋接相關的代碼,因此使用分類拓展,這樣也能夠對代碼進行解耦。

這裏有一個注意點:若是自帶的屬性是block類型的話,屬性名必須以on開頭

RCT_CUSTOM_VIEW_PROPERTY可讓咱們添加一些更爲複雜的屬性。因爲cityIdsubwayDataFilterMenuGeographicController這個子菜單才須要的,若是把它們設置爲FHTFilterMenu的屬性並不合適,而FilterMenuGeographicController咱們並無暴露給JS,因此咱們可使用RCT_CUSTOM_VIEW_PROPERTY對沒有暴露給JS的對象進行屬性傳遞。

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調用原生組件的方法

RCT_EXPORT_METHOD用來提供原生方法給JS調用。RCT_EXPORT_METHOD(showFilterMenuOnView:(nonnull NSNumber *)containerTag filterMenuTag:(nonnull NSNumber *)filterMenuTag)用來實現將子菜單添加到SearchHousePage,其實現以下:

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代碼用來表示SearchHousePagefilterMenuTag則表示篩選條。這裏有一個注意點:不能使用self.view的方式由於會建立出一個新的FHTFilterMenu對象,更不能在- (UIView *)view中使用一個指針對建立出來的View進行引用,若是你的組件在多個頁面都用使用的話,是會出問題的

另外,因爲iOS的UI操做是要放在主線程完成的,因此最好methodQueue指定爲主線程。

結尾

到這裏整個SearchHousePage頁面的開發已經完成,若是須要查看完整代碼的話,在代碼傳送門--NNHybrid中。

參考: Native Modules Native UI Components

相關文章
相關標籤/搜索