一、前言
我在之前的关于react-navigation 3.x中也提到过,react-navigation在混合中使用会报错:undefined is not an object (evaluating 'RNGestureHandlerModule.State')
,
之前一直解决不了,直到我收到以为网友一个帅气的人
给我留言说了一个解决方法,但是他的应该是IOS的解决方法,最后我在他的一篇文章里提到里一个解决这个问题的链接
以及React Native Android 开发巨坑这两篇文章中得到里解决方法:
二、解决方法
在自定义ReactActivity中使用RNGestureHandlerEnabledRootView
首先我使用react-native link react-native-gesture-handler
链接依赖项了,但是在我自定义的ReactActivity中使用RNGestureHandlerEnabledRootView
类,却找不到
通过React Native Android 开发巨坑这两篇文章中知道了react-native link
命令基本没法用,因为RN在这里不是一个Application
,入口文件名也不一定是MainActivity.java
,所以基本所有的Native库,都要手动Link.
1) 修改 settings.gradle
......
include ':react-native-gesture-handler'
project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-gesture-handler/android')
注意目录地址:如果是普通RN项目,一般是相对路径 ../node_modules/
,但是Native接入RN的话,一般RN代码已经是在Android的目录了,所以不加 ..
,具体还是看项目结构 。引入各种库的时候,要时刻关注目录的问题。
2) 修改 app/build.gradle
dependencies {
......
implementation project(':react-native-gesture-handler')
}
此时,android项目Sync Now
一下,就有了RNGestureHandlerEnabledRootView
类
3) 在自定义的ReactActivity中使用RNGestureHandlerEnabledRootView
类
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
public class ReactPageActivity extends ReactActivity {
@Override
protected String getMainComponentName() {
return "RNApp";
}
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this,getMainComponentName()){
@Override
protected ReactRootView createRootView() {
return new RNGestureHandlerEnabledRootView(ReactPageActivity.this);
}
};
}
}
4) 在自定义的Application中添加RNGestureHandlerPackag
类
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;
import java.util.Arrays;
import java.util.List;
public class MyApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNGestureHandlerPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
至此,上面的问题就解决了!!!