React Native与原生通信
在React Native中与原生代码通信通常使用react-native link
命令链接的原生模块。以下是一个简单的例子,展示如何从React Native调用原生Android方法。
首先,在Java中定义原生模块:
// MyNativeModule.java
package com.myapp;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;
public class MyNativeModule extends ReactContextBaseJavaModule {
MyNativeModule(ReactApplicationContext context) {
super(context);
}
@Override
public String getName() {
return "MyNativeModule";
}
@ReactMethod
public void sampleMethod(String input, Callback callback) {
// 原生逻辑
String result = "Received: " + input;
callback.invoke(result);
}
}
然后,注册模块:
// MainApplication.java
package com.myapp;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
// 添加其他的packages如有必要
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
}
最后,在React Native中使用:
// MyComponent.js
import React, { Component } from 'react';
import { NativeModules } from 'react-native';
export default class MyComponent extends Component {
componentDidMount() {
NativeModules.MyNativeModule.sampleMethod('Hello', (result) => {
console.log(result); // 输出: Received: Hello
});
}
render() {
return (
<View>
<Text>Sample Module Interaction</Text>
</View>
);
}
}
确保你已经运行了react-native link
命令来链接原生模块。这样,你就可以在React Native中通过NativeModules
访问原生模块了。
评论已关闭