Android开发学习之路--React-Native混合开发初体验

准备

1. Expo尝鲜

1.1 环境安装:

  • 1.1.1 npm来安装create-react-native-app命令行
npm install -g create-react-native-app
  • 1.1.2 创建一个名为“RNExpo”的新的React Native项目
create-react-native-app RNExpo
cd RNExpo
npm start

然后到iOS和android应用商店下载App“Expo”, 扫描二维码就可以看到效果了。

注:其中ios直接打开相机扫描识别即可

2. Android混合开发

2.1 gradle配置

  • 2.1.1 修改主工程build.gradle:
allprojects {
    repositories {
        maven{ url "$rootDir/node_modules/react-native/android"}
    }
}

其中url的路径需要修改为对应的node_modules的的react-native的路径。

  • 2.1.2 修改app中的build.gradle:
compile "com.facebook.react:react-native:+" // From node_modules.

这里加上react-native的依赖

2.2 注册ReactNativeHost

  • 2.2.1 新建MyReactPackage,包含需要暴露的模块
public class MyReactPackage implements ReactPackage {

    public UserInfoModule userInfoModule;

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        userInfoModule = new UserInfoModule(reactContext);
        modules.add(userInfoModule);
        return modules;
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

这里主要是为了实现js与原生的交互。可以增加更多的module。

  • 2.2.2 创建一个ReactContextBaseJavaModule

这里暴露用户的一些数据定义为UserInfoModule

public class UserInfoModule extends ReactContextBaseJavaModule {

    public UserInfoModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

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

    @ReactMethod
    public void rnCallNativeFromPromise(String msg, Promise promise) {

        Log.e("---", "adasdasda");
        // 1.处理业务逻辑...
        String result = "处理结果:" + msg;
        // 2.回调RN,即将处理结果返回给RN
        promise.resolve(result);
    }
}

暴露了rnCallNativeFromPromise方法。需要使用@ReactMethod注解

  • 2.2.3 Application实现ReactApplication
public class MyApplication extends Application implements ReactApplication {

    private static final MyReactPackage myReactPackage = new MyReactPackage();

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
            return false;
        }

        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(new MainReactPackage(), myReactPackage);
        }
    };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    /**
     * 获取 reactPackage
     * @return
     */
    public static MyReactPackage getReactPackage() {
        return myReactPackage;
    }
}

到此基本上前期环境都已经搭建ok了。

2.3 新建ReactActivity

新建MyReactActivity

public class MyReactActivity extends ReactActivity {

    @Nullable
    @Override
    protected String getMainComponentName() {
        return "App";
    }
}

这里的getMainComponentName就是js中

AppRegistry.registerComponent('App', () => App);

这样我们就新建了一个Activity,实际加载的js的component就会在这个activity中渲染了。

3. Js开发

基于1中的脚手架create-react-native-app生成的项目,接着开发。

3.1 暴露

npm run eject

不过暴露之后用不了expo了

3.2 支持TypeScript

TypeScript支持更多的语法糖和类型。

  • 3.2.1 安装typescript
cd RNExpo
npm install -g typescript
npm install typescript
tsc --init

# 未安装 tsd 则先安装再进行项目初始化
npm install -g tsd

tsd init && tsd install react-native --save
  • 3.2.2 配置tsconfig.json
{
  "compilerOptions": {
    "target": "es6",
    //    "allowJs": true,
    "jsx": "react",
    //    "outDir": "./dist",
    "sourceMap": false,
    "noImplicitAny": false,
    "skipLibCheck": true
  },
  "include": [
    "typings/**/*.d.ts",
    "*.ts",
    "*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}
  • 3.2.3 安装@types/xxx
    在使用typescript的第三方开源组件时候,需要安装对应的typescript的组件,如下所示:
npm install @types/react
npm install @types/react-dom
npm install @types/react-native
npm install @types/react-native-swiper
npm install @types/react-navigation
  • 3.2.4 编译
tsc

编译成功后会在对应的xxx.tsx下有个xxx.js。因为实际我们还是运行的js代码。

3.3 新建App.tsx

新建Component

import * as React from 'react'
import {StyleSheet, Text, View} from 'react-native';

function hello(): string {
    return 'Hello React Native!'
}

export default class App extends React.Component {

    render() {
        return (
            <View style={styles.container}>
                <Text>{hello()}</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
});

在index.js中注册App

import {AppRegistry} from 'react-native';
import HelloRNActivity from "App";

AppRegistry.registerComponent("App", () => App);

3.4 打包

  • 3.4.1 安装react-native-cli
npm install -g react-native-cli
  • 3.4.2 打包到Android的assets中
    这里实现了一个脚本 install.sh,实现如下所示:
#!/bin/sh

ASSETS_PATH="../XXX/RNAndroid/src/main/assets"
RES_PATH="../XXX/RNAndroid/src/main/res/drawable-mdpi"

if [ ! -d "output" ]; then
    mkdir -p output/bundle
    mkdir -p output/res
fi

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

if [ ! -d "$ASSETS_PATH" ]; then
    mkdir -p $ASSETS_PATH
fi

if [ ! -d "$RES_PATH" ]; then
    mkdir -p $RES_PATH
fi

cp output/bundle/* $ASSETS_PATH
cp output/res/drawable-mdpi/* $RES_PATH

该脚本会把需要的bundle文件和资源文件拷贝到Android的工程项目中。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值