React-Native 实现native模块供js调用

实现需要让js使用的方法,类和方法标记@objc以让OC可以发现

//XKRouter.swift
import Foundation
import React

/*
 需要暴露给rn调用的方法第一个参数记得加_,否则会报错
 */

@objc(XKRouter)//这是暴露给OC的类名
class XKRouter: NSObject {
    
    @objc func getRedirectUrl(_ urlHandler: RCTResponseSenderBlock) {
        urlHandler([HostUrl + "checkout/cart"])
    }
    
    @objc func testOneParamMethod(_ param: String) {
        print("原生方法带一个参数无返回值函数被js调用: \(param)")
    }
    
    @objc func testTwoParamsMethod(_ param1: String, param2: String) {
        print("原生方法带两个参数无返回值函数被js调用: \(param1) \(param2)")
    }
    
    @objc func testClosureParamsMethod(_ closure: RCTResponseSenderBlock) {
        closure([1, "2", "hello-world"])
        print("原生方法带闭包参数无返回值函数被js调用: \(closure)")
    }
    
    @objc func testPromiseMethod(_ reslove: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
        request(Router.FetchCart, success: { (response: HTTPURLResponse?, json: AnyObject) in
            reslove([response!, json])
        }) { (_: AnyObject?, error: NSError?) in
            reject(nil, nil, error)
        }
    }
    
}

OC实现RCTBridgeModule以暴露一个本地模块XKRouter给js

//  XKRouterBridge.m
#import 

@interface RCT_EXTERN_MODULE(XKRouter, NSObject)

RCT_EXTERN_METHOD(getRedirectUrl:(nonnull RCTResponseSenderBlock)callback)

RCT_EXTERN_METHOD(testOneParamMethod:(nonnull NSString *)string)

RCT_EXTERN_METHOD(testTwoParamsMethod:(nonnull NSString *)param1 param2:(nonnull NSString *)param2 )

RCT_EXTERN_METHOD(testClosureParamsMethod:(nonnull RCTResponseSenderBlock)callback)

RCT_EXTERN_METHOD(testPromiseMethod:(RCTPromiseResolveBlock)reslove reject:(RCTPromiseRejectBlock)reject)

@end

js使用

import {NativeModules} from 'react-native'
const XKRouter = NativeModules.XKRouter
XKRouter.getRedirectUrl((url) => {
      console.log(url, '来自native')
    })
    XKRouter.testOneParamMethod('哈哈')
    XKRouter.testTwoParamsMethod('hello', 'world')
    XKRouter.testClosureParamsMethod((param1, param2, param3) => {
      console.log(param1, param2, param3, 'params from native')
    })
    XKRouter.testPromiseMethod()
      .then((json) => console.log(json, 'this is json'))
      .catch((error) => console.log(error, 'this is error'))

你可能感兴趣的:(React-Native 实现native模块供js调用)