美文网首页
已有Android项目接入ReactNative(一)

已有Android项目接入ReactNative(一)

作者: 刀放下好好说话 | 来源:发表于2019-12-10 18:16 被阅读0次

1.初始化

项目根目录执行 npm init ,一路enter。项目的根目录会出现package.json文件。

2.修改package.json

在script下添加 "start": "node node_modules/react-native/local-cli/cli.js start"

3.安装react和react-native模块

根目录执行 npm install --save react react-native ,安装的时间会比较久。如果失败了重复执行一次。直到成功显示“added xxx packages from xxx in xxx”。

4.引入React-Native依赖

app的gradle文件加下增加implementation "com.facebook.react:react-native:+"
项目的gradle文件allprojects下增加

    allprojects {
        repositories {
            //这两个配置一定不能少
            maven {
                url "$rootDir/node_modules/react-native/android"
            }
            maven {
                url("$rootDir/node_modules/jsc-android/dist")
            }
            google()
            jcenter()
        }
    }

注意一定要查看引入的React-Native版本,如果说是0.20.1就是默认的引入,需要修改为最新的版本0.61.5。

5.编写React组件

新建一个文件夹,主要放js文件,编写一个Hello ReactNative组件,调用AppRegistry注册组件。

6.引入React组件

Application配置:

    public class MyApplication extends Application implements ReactApplication {
    
        private ReactNativeHost reactNativeHost = new ReactNativeHost(this) {
            @Override
            public boolean getUseDeveloperSupport() {
                return false;
            }
    
            @Override
            protected List<ReactPackage> getPackages() {
                return Arrays.<ReactPackage>asList(
                        new MainReactPackage(),
                );
            }
    
            @Override
            protected String getJSMainModuleName() {
                return "index.android";
            }
        };
    
        @Override
        public ReactNativeHost getReactNativeHost() {
            return reactNativeHost;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            SoLoader.init(this, false);
        }
    }

6.1 完全的React页面

直接新建Activity,继承ReactActivity就可以了。

    public class JustReactActivity extends ReactActivity {
    
        @Nullable
        @Override
        protected String getMainComponentName() {
            return "HelloReactNative";
        }
    }

这个HelloReactNative就是在index.android.js里面注册的一个组件,index.android.js文件放到根目录下,就是ReactNative的入口:

    import React, {Component} from 'react';
    import {
        AppRegistry,
        StyleSheet,
        Text,
        View
    } from 'react-native';
    
    export default class HelloReactNative extends Component {
    
        render() {
            return (
                <View style={styles.container}>
                    <Text style={styles.welcome}>
                        Welcome to React Native!
                    </Text>
                    <Text style={styles.instructions}>
                        我是 ReactNative
                    </Text>
                    <Text style={styles.instructions}>
                        Press Cmd+R to reload,{'\n'}
                        Cmd+D or shake for dev menu
                    </Text>
                </View>
            );
        }
    }
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#F5FCFF',
        },
        welcome: {
            fontSize: 20,
            textAlign: 'center',
            margin: 10,
        },
        instructions: {
            textAlign: 'center',
            color: '#333333',
            marginBottom: 5,
        },
    });
    
    AppRegistry.registerComponent('HelloReactNative', () => HelloReactNative);

6.2 部分原生部分混入了React页面

原生页面引入ReactRootView,加载js内容:

    public class PartReactActivity extends AppCompatActivity {
    
        private ReactInstanceManager reactInstanceManager;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_part_react);
    
            ReactRootView reactRootView = findViewById(R.id.root_view);
            reactInstanceManager = ReactInstanceManager.builder()
                    .setApplication(getApplication())
                    .setCurrentActivity(this)
                    .setBundleAssetName("index.android.bundle")
                    .setJSMainModulePath("index.android")
                    .addPackage(new MainReactPackage())
                    .setUseDeveloperSupport(false)
                    .setInitialLifecycleState(LifecycleState.RESUMED)
                    .build();
            reactRootView.startReactApplication(reactInstanceManager, "HelloReactNative", null);
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            if(reactInstanceManager != null) {
                reactInstanceManager.onHostPause(this);
            }
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            if(reactInstanceManager != null) {
                reactInstanceManager.onHostResume(this);
            }
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if(reactInstanceManager != null) {
                reactInstanceManager.onHostDestroy(this);
            }
        }
    }

7.关于报错

7.1 SoLoader没有调用

Application的onCreate()下调用:

    @Override
    public void onCreate() {
        super.onCreate();
        SoLoader.init(this, false);
    }

7.2 enableHermes设置

app的gradle下配置如下:

    project.ext.react = [
            enableHermes: false,
    ]
    
    def jscFlavor = 'org.webkit:android-jsc:+'
    def enableHermes = project.ext.react.get("enableHermes", false);
    
    dependencies {
        if (enableHermes) {
            def hermesPath = "../../node_modules/hermesvm/android/";
            debugImplementation files(hermesPath + "hermes-debug.aar")
            releaseImplementation files(hermesPath + "hermes-release.aar")
        } else {
            implementation jscFlavor
        }
    }

7.3 找不到SwipeRefreshLayout

app的gradle下引入:

    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha03'

8. 运行

至此已经配置完全了,运行需要首先在/app/src/main下创建assets文件,然后执行bundle命令:


    react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output app/src/main/assets/index.android.bundle --assets-dest app/src/main/res

如何你在assets下发现了index.android.bundle说明你已经成功实现接入了。

点一下run看一下效果吧。

相关文章

网友评论

      本文标题:已有Android项目接入ReactNative(一)

      本文链接:https://www.haomeiwen.com/subject/ougggctx.html