React Native 与 嵌入Android原生与Activity页面互相跳转
在React Native项目中,你可以通过自定义原生模块来实现与Android原生Activity页面的互相跳转。以下是一个简单的例子,展示如何从React Native跳转到一个原生Activity,并返回。
- 创建一个自定义模块
NativeToRNActivityModule.java
:
package com.yourpackage;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.bridge.Arguments;
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 NativeToRNActivityModule extends ReactContextBaseJavaModule {
private static final String MODULE_NAME = "NativeToRNActivityModule";
private Activity mCurrentActivity;
public NativeToRNActivityModule(ReactApplicationContext context) {
super(context);
mCurrentActivity = getCurrentActivity();
}
@Override
public String getName() {
return MODULE_NAME;
}
@ReactMethod
public void startNativeActivity(Callback callback) {
Intent intent = new Intent(mCurrentActivity, NativeActivity.class);
mCurrentActivity.startActivityForResult(intent, 123);
mCallback = callback;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 123 && mCallback != null) {
Bundle bundle = data.getExtras();
String result = bundle.getString("result");
mCallback.invoke(result);
}
}
private Callback mCallback;
}
- 在
NativeActivity.java
中,当需要返回数据到React Native时,可以这样做:
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("result", "Some data from Native Activity");
intent.putExtras(bundle);
setResult(RESULT_OK, intent);
finish();
- 在React Native项目中,注册模块:
// MainApplication.java or your own native module registration file
import com.yourpackage.NativeToRNActivityModule; // import the module
public class MainApplication extends Application implements Reac
评论已关闭