在 react-native 中从 TypeScript 调用本机函数

Calling native function from TypeScript in react-native

最近我需要一个简单的函数来与本机代码交互,但我决定不构建一个包,因为它不会很有用。我创建了 java 文件,就像它们来自插件一样,并在 MainApplication 中注册了它。

我正在使用打字稿,所以现在我正在努力处理 rn 到 java 的交互。我尝试使用如下 js 文件:

import NativeModules from 'react-native';
const AndroidService = NativeModules;
export default { AndroidService }

但是我必须定义类型(来自 vs 代码的消息):

Property 'play' does not exist on type '{ AndroidService: typeof import("/home/karol/Git/TailosiveHub-react/node_modules/@types/react-native/index"); }'.

我尝试在项目的根目录中创建一个 index.d.ts 文件,但这不起作用。

如何在打字稿中为本机模块定义类型?

主要应用程序:

@Override
protected List<ReactPackage> getPackages() {
    @SuppressWarnings("UnnecessaryLocalVariable")
    List<ReactPackage> packages = new PackageList(this).getPackages();
    // Packages that cannot be autolinked yet can be added manually here, for example:
    // packages.add(new MyReactNativePackage());
    packages.add(new AndroidServicePackage());
    // packages.add(new MainReactPackage());
    return packages;
}

Android服务包:

@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
  return Arrays.<NativeModule>asList(new AndroidServiceModule(reactContext));
}

安卓服务模块:

@Override
public String getName() {
    return "AndroidService";
}

方法:

@ReactMethod
public void play(String streamingURL/*, ReadableMap options*/) {
  doSomething();
}

NativeModules 导入包含内部的本机模块,因此您只需将 AndroidService 模块提取为 属性。

import NativeModules from 'react-native';
const { AndroidService } = NativeModules
export default { AndroidService }

或者,您可以像这样简单地导出它:

import NativeModules from 'react-native';
exports.default = NativeModules.AndroidService;

如果您在提供给 React Native 的包中添加了相应的名为 AndroidService 的本机模块,这应该会给您想要的结果。

取自React Native's documentation on Native Modules

您必须像这样在 AndroidService 的赋值周围添加括号(这称为解构):

import { NativeModules } from 'react-native'; 
export const { AndroidService } = NativeModules

然后在另一个文件中你可以像这样使用它:

import { AndroidService } from 'path/to/exporting/file';

...

AndroidService.play("YOUR_URL"); 

我通过修复插件 ts 文件中的导入来修复它。 现在看起来像这样:

import { NativeModules } from 'react-native';
const AndroidService = NativeModules.AndroidService;
export default AndroidService;