【问题标题】:How to convert react js array [] to NSArray in iOS and string[] in Android?如何将 React js 数组 [] 转换为 iOS 中的 NSArray 和 Android 中的 string[]?
【发布时间】:2019-08-26 03:32:17
【问题描述】:

我是一个使用 react-native 的跨平台项目的新手,我想知道如何将 javascript 字符串数组转换为 Java 数组 (String[]) 和 iOS NSArray。

例如, 我的 JS 组件有

constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      devices: [],
      selectedDevices:[]
    };
  }

我的 Android 原生模块期望如下 -

public void disableDevices(String[] deviceNames){
...

}

有人可以帮忙吗?

【问题讨论】:

  • 为什么要在 iOS 中将其数组 [] 转换为 NSArray 而在 Android 中转换为 string[]?
  • 我需要将此结果传递给本机模块。

标签: reactjs react-native react-router


【解决方案1】:

这是一个使用传递数组调用本机方法的示例。希望这会对你有所帮助。

安卓

@ReactMethod
public void yourMethod(ReadableArray yourArray, final Promise promise) {

}

iOS

// YourModule.h
+(void) yourMethod:(NSArray *)yourArray resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject;

// YourModule.m
+ (void) yourMethod:(NSArray *)yourArray
                         resolver:(RCTPromiseResolveBlock)resolve
                         rejecter:(RCTPromiseRejectBlock)reject
{

}

JS

import { NativeModules } from 'react-native';
const { YourModule } = NativeModules;
...

YourModule.yourMethod([1, 2, 3]);

您可以阅读有关 nativeModules 的更多信息here

【讨论】:

    猜你喜欢
    • 2014-05-03
    • 2019-03-28
    • 2012-08-31
    • 2012-02-24
    • 2011-12-26
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 2017-04-14
    相关资源
    最近更新 更多