React Native中使用Kotlin

写在前面

github项目地址

目前该项目做了部分修改,但仍可以clone之后使用git回退到第二个commit的版本查看计算A+B测试的完整代码,具体步骤:

  1. git clone https://github.com/zih-an/RNwithKotlin.git
  2. cd RNwithKotlin
  3. git log,找到以下红色箭头 modify the readme 的版本在这里插入图片描述4. git checkout 40c057ddc645762d3b31126f923971c1890a57fa 即可!(此时该项目即为本博客的A+B示例完整版)

介绍

现希望用 kotlin 计算 a+b 的值返回,用 react-native 调用并显示结果

  • a+b在文件AlertManager.kt
    • fun trigger(a:Double, b:Double, resPromise:Promise)
  • react-native只能使用async & await接收结果,参见文件App.js
  • 此外,java和kotlin同时存在并不影响,因此react-native生成的java文件不用动

详细步骤

1 初始化React Native项目

详情参考官网
npx react-native init RNwithKotlin

2 使用Android Studio打开 android 文件夹

2.1 android/build.gradle

buildscript {
  //== add 1. ==
  ext.kotlin_version = "1.4.32"
  ...
  repositories {
    ...
    //== add 2. ==
    maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
  }
  dependencies {
    ...
    //== add 3. ==
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  }
}

allprojects {
  repositories {
    ...
    //== add 4. ==
    jcenter()
    maven { url 'https://www.jitpack.io' }
  }
}

2.2 android/app/build.gradle

/**============ add here ===============*/
apply plugin: "kotlin-android"

...

android {
  ...
//============== add here =======================
  buildFeatures {
    viewBinding true
  }
}

dependencies {
  ...
//============== add here =======================
  implementation "org.jetbrains.kotlin:kotlin-stdlib"
  ...
}

2.3 aplusb.kt

package com.rnwithkotlin

import android.view.View
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
import java.util.*

class AplusB:ReactPackage {
    override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
        val modules = ArrayList<NativeModule>()
        modules.add(AlertManager(reactContext))
        return modules
    }

    override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
        return Collections.emptyList<ViewManager<*, *>>()
    }
}

2.4 AlertManager.kt

package com.rnwithkotlin

import android.content.Intent
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.Promise;

class AlertManager(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
    private final var TAG = "AlertMangager";
    override fun getName(): String {
        return "Alt"
    }

    @ReactMethod
    //=========== a+b here ===============
    // have to use promise to get the result async.
    fun trigger(a:Double, b:Double, resPromise:Promise) {
        resPromise.resolve(a+b);
    }

}

2.5 MainApplication.java

@Override
protected List<ReactPackage> getPackages() {
  @SuppressWarnings("UnnecessaryLocalVariable")
  List<ReactPackage> packages = new PackageList(this).getPackages();

//============================= add here ===============================
  packages.add(new AplusB());

  // Packages that cannot be autolinked yet can be added manually here, for example:
  // packages.add(new MyReactNativePackage());
  return packages;
}

3 export the module

in kotlin.js:

import {NativeModules} from 'react-native';
const {Alt} = NativeModules;
console.log('Alt: ', Alt);
export default Alt;

现在可以调用 Alt.trigger(a,b),例如App.js 中:

import React from 'react';
import {View, Text} from 'react-native';
import Alt from './kotlin';

export default class App extends React.Component {
  state = {res: 0};

  async componentDidMount() {
    let tmp = await Alt.trigger(10, 3); // test value here!
    console.log(tmp);
    this.setState({res: tmp});
  }

  render() {
    return (
      <View>
        <Text>Hello ReactNative</Text>
        <Text>this is a+b from kotlin: {this.state.res}</Text>
      </View>
    );
  }
}

4 测试

npx react-native run-android

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值