桥接原生

为什么需要桥接原生

实现react层JS实现不了的需求:

  1. 复杂、高性能组件:复杂表格、视频播放等
  2. 原生层开发能力:传感器编程、widget等
  3. 平台属性:系统信息、设备信息等
  4. 对接三方应用:相机、相册、地图等

桥接原生实现JS调用原生方法

1. 编写并注册原生层方法

AppModule.kt

package com.awesomeproject.rn

import com.awesomeproject.BuildConfig
import com.awesomeproject.utils.DeviceUtil
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod

/**
 *
 * created by ZhangPan on 2024/4/22
 */
class AppModule(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) {
    override fun getName(): String {
        return "App"
    }

    @ReactMethod
    fun openGallery() {
        if (currentActivity == null) return
        DeviceUtil.openGallery(currentActivity)
    }

    @ReactMethod
    fun getVersionName(promise: Promise) {
        val version = BuildConfig.VERSION_NAME
        if (version == null) {
            promise.reject(Throwable("获取版本失败"))
        } else {
            promise.resolve(version)
        }
    }
}

DemoReactPackager.kt 使用AppModule

package com.awesomeproject.rn

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.ReactShadowNode
import com.facebook.react.uimanager.ViewManager
import java.util.Collections

/**
 *
 * created by ZhangPan on 2024/4/22
 */
class DemoReactPackager : ReactPackage {
    override fun createNativeModules(context: ReactApplicationContext): MutableList<NativeModule> {
        return mutableListOf<NativeModule>().apply {
            add(AppModule(context))
        }
    }

    override fun createViewManagers(context: ReactApplicationContext): MutableList<ViewManager<View, ReactShadowNode<*>>> {
        return Collections.emptyList()
    }
}

Application中注册

package com.awesomeproject

import android.app.Application
import com.awesomeproject.rn.DemoReactPackager
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.flipper.ReactNativeFlipper
import com.facebook.soloader.SoLoader

class MainApplication : Application(), ReactApplication {

  override val reactNativeHost: ReactNativeHost =
      object : DefaultReactNativeHost(this) {
        override fun getPackages(): List<ReactPackage> =
            PackageList(this).packages.apply {
              // Packages that cannot be autolinked yet can be added manually here, for example:
              // add(MyReactNativePackage())
              add(DemoReactPackager())
            }

        override fun getJSMainModuleName(): String = "index"

        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG

        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
      }

  override val reactHost: ReactHost
    get() = getDefaultReactHost(this.applicationContext, reactNativeHost)

  override fun onCreate() {
    super.onCreate()
    SoLoader.init(this, false)
    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
      // If you opted-in for the New Architecture, we load the native entry point for this app.
      load()
    }
    ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)
  }
}

2. JS层调用原生方法

NativePage.tsx

import { Button, NativeModules, StyleSheet, View } from 'react-native'

export default () => {
    return(
        <View style={styles.root}>
            <Button 
                title='调用原生方法'
                onPress={() => {
                    const { App } = NativeModules;
                    // App?.openGallery() 
                    App?.getVersionName().then((data: string) => {
                        console.log(data)
                    })
                }}
            />
        </View>
    );

}

const styles = StyleSheet.create({
    root: {
        "width": '100%',
        "height": '100%',
        backgroundColor: 'red'
    },
})

桥接原生常量

override fun getConstants(): Map<String, Any> {
        return mutableMapOf<String, Any>(
            "VersionName" to BuildConfig.VERSION_NAME,
            "VersionCode" to BuildConfig.VERSION_CODE
        )
    }

JS调用原生:

const { VersionName, VersionCode } = App;
console.log(`VersionNmae: ${VersionName}, VersionCode: ${VersionCode}`)

桥接原生原子组件

1. 实现一个原生自定义组件View

InfoView.kt

package com.awesomeproject.view

import android.view.LayoutInflater
import android.widget.LinearLayout
import com.awesomeproject.R
import com.facebook.react.uimanager.ThemedReactContext

/**
 *
 * created by ZhangPan on 2024/4/23
 */
class InfoView(context: ThemedReactContext) : LinearLayout(context) {
    init {
        initView(context)
    }

    private fun initView(context: ThemedReactContext) {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_infoview, null, false)
        val layoutParams =
            LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        this.addView(view, layoutParams)
    }
}

2. 创建ViewManager,用于接管原生自定义组件的属性和行为,并把ViewManager注册到ReactPackage中。

InfoViewManager.kt

package com.awesomeproject.viewManager

import com.awesomeproject.view.InfoView
import com.facebook.react.uimanager.SimpleViewManager
import com.facebook.react.uimanager.ThemedReactContext

/**
 *
 * created by ZhangPan on 2024/4/23
 */
class InfoViewManager: SimpleViewManager<InfoView>() {
    override fun getName(): String {
        return "NativeInfoView"
    }

    override fun createViewInstance(context: ThemedReactContext): InfoView {
        return InfoView(context)
    }
}

DemoReactPackager.kt

package com.awesomeproject.rn

import com.awesomeproject.viewManager.InfoViewManager
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager

/**
 *
 * created by ZhangPan on 2024/4/22
 */
class DemoReactPackager : ReactPackage {
    override fun createNativeModules(context: ReactApplicationContext): MutableList<NativeModule> {
        return mutableListOf<NativeModule>().apply {
            add(AppModule(context))
        }
    }

    override fun createViewManagers(context: ReactApplicationContext): MutableList<ViewManager<*, *>> {
        val mutableListOf = mutableListOf<ViewManager<*, *>>()
        mutableListOf.add(InfoViewManager())
        return mutableListOf
    }

}

3. 在JS层导入原生组件,并封装导出JS模块

import { StyleSheet, ViewProps, requireNativeComponent } from "react-native"


type NativeInfoViewType = ViewProps | {
    //这部分是自定义的属性
}

const NativeInfoView =  requireNativeComponent<NativeInfoViewType>('NativeInfoView');

export default () => {
    return(
        <NativeInfoView style={styles.inforView}/>
    )
}

const styles = StyleSheet.create({
    inforView: {
        width:'100%',
        height: '100%'
    }
})

4. 使用@ReactProp定义组件属性

InfoViewManager.kt中:

@ReactProp(name = "name")
    fun setName(infoView: InfoView, name: String) {
        infoView.setName(name)
    }

    @ReactProp(name = "desc")
    fun setDesc(infoView: InfoView, desc: String) {
        infoView.setDesc(desc)
    }

InfoView.kt:

package com.awesomeproject.view

import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.TextView
import com.awesomeproject.R
import com.facebook.react.uimanager.ThemedReactContext

/**
 *
 * created by ZhangPan on 2024/4/23
 */
class InfoView(context: ThemedReactContext) : LinearLayout(context) {
    private var tvDesc: TextView? = null
    private var tvName: TextView? = null

    init {
        initView(context)
    }

    private fun initView(context: ThemedReactContext) {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_infoview, null, false)
        tvName = view.findViewById(R.id.tvName)
        tvDesc = view.findViewById(R.id.tvDesc)
        val layoutParams =
            LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        this.addView(view, layoutParams)
    }

    fun setName(name: String) {
        tvName?.setText(name)
    }

    fun setDesc(desc: String) {
        tvDesc?.setText(desc)
    }
}

js中使用:

import { StyleSheet, ViewProps, requireNativeComponent } from "react-native"


type NativeInfoViewType = ViewProps | {
    //这部分是自定义的属性
    name: string,
    desc: string
}

const NativeInfoView =  requireNativeComponent<NativeInfoViewType>('NativeInfoView');

export default () => {
    return(
        <NativeInfoView 
            style={styles.inforView}
            name='尼古拉斯-拜登'
            desc="美国总统"
        />
    )
}

const styles = StyleSheet.create({
    inforView: {
        width:'100%',
        height: '100%'
    }
})

5. 原生组件回调JS层方法

InfoView.kt 做了一个点击事件,然后回调给JS层:

override fun onClick(view: View?) {
        if (view == tvName) {
            nameValue = if (nameValue == "尼古拉斯-段坤") {
                "尼古拉斯-拜登"
            } else {
                "尼古拉斯-段坤"
            }
            setName(nameValue)
            val params = Arguments.createMap()
            params.putString("value", nameValue)
            val context = context as ReactContext
            context.getJSModule(RCTEventEmitter::class.java).receiveEvent(id, "onValueChanged", params)
        }
    }

InfoViewManager.kt 重写getExportedCustomBubblingEventTypeConstants这个方法:

override fun getExportedCustomBubblingEventTypeConstants(): MutableMap<String, Any>? {
        return MapBuilder.builder<String, Any>()
                        .put("onValueChanged",
                                MapBuilder.of(
                                    "phasedRegistrationNames",
                                        MapBuilder.of("bubbled", "onValueChanged")
                                )
                            ).build()
    }

NativeInfoView.tsx 使用如下:

import { StyleSheet, ViewProps, requireNativeComponent } from "react-native"


type NativeInfoViewType = ViewProps | {
    //这部分是自定义的属性
    name: string,
    desc: string,
    onValueChanged: (e: any) => void
}

const NativeInfoView =  requireNativeComponent<NativeInfoViewType>('NativeInfoView');

export default () => {
    return(
        <NativeInfoView 
            style={styles.inforView}
            name='尼古拉斯-拜登'
            desc="美国总统"
            onValueChanged={(e: any) => {
                console.log(e.nativeEvent.value)
            }}
        />
    )
}

const styles = StyleSheet.create({
    inforView: {
        width:'100%',
        height: '100%'
    }
})

6. 公共原生组件方法给JS层调用

NativeInfoView.tsx中定义senCommands方法:

import { useEffect, useRef } from "react";
import { StyleSheet, UIManager, ViewProps, findNodeHandle, requireNativeComponent } from "react-native"


type NativeInfoViewType = ViewProps | {
    //这部分是自定义的属性
    name: string,
    desc: string,
    onValueChanged: (e: any) => void
}

const NativeInfoView =  requireNativeComponent<NativeInfoViewType>('NativeInfoView');

export default () => {
    const ref = useRef(null);
    useEffect(() => {
        setTimeout(() => {
            sendCommands("setName", ["尼古拉斯-段坤"])
        }, 3000)
    }, [])

    const sendCommands = (command: string, params: any[]) => {
        const viewId = findNodeHandle(ref.current);
        // @ts-ignore
        const commands =  UIManager.NativeInfoView.Commands[command].toString();
        UIManager.dispatchViewManagerCommand(viewId, commands, params);
    }

    return(
        <NativeInfoView 
            ref={ref}
            style={styles.inforView}
            name='尼古拉斯-拜登'
            desc="美国总统"
            onValueChanged={(e: any) => {
                console.log("--- " + e.nativeEvent.value)
            }}
        />
    )
}

const styles = StyleSheet.create({
    inforView: {
        width:'100%',
        height: '100%'
    }
})

InfoViewManager.kt中增加如下代码:

val SET_NAME_CODE = 100

    override fun getCommandsMap(): MutableMap<String, Int>? {
        return MapBuilder.of("setName", SET_NAME_CODE)
    }

    override fun receiveCommand(view: InfoView, commandId: String?, args: ReadableArray?) {
        val command = commandId?.toInt()
        if (command == SET_NAME_CODE) {
            if (args != null && args.size() > 0) {
                val nameValue = args.getString(0)
                view.setName(nameValue)
            }
        } else {
            super.receiveCommand(view, commandId, args)
        }
    }

InfoView.kt中增加setName方法:

fun setName(name: String) {
        this.nameValue = name
        val value = if (nameValue == "尼古拉斯-段坤") {
            "尼古拉斯-拜登"
        } else {
            "尼古拉斯-段坤"
        }
        tvName?.setText(value)
    }

桥接原生容器组件

  1. 实现一个原生容器组件

InfoViewGroup.kt

package com.awesomeproject.view

import android.widget.LinearLayout
import com.facebook.react.uimanager.ThemedReactContext

/**
 *
 * created by ZhangPan on 2024/4/24
 */
class InfoViewGroup(context: ThemedReactContext) : LinearLayout(context) {

}
  1. 创建ViewGroupManager,注册行为和ViewManager一致

InfoViewGroupManager.kt

package com.awesomeproject.viewManager

import com.awesomeproject.view.InfoViewGroup
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.ViewGroupManager

/**
 *
 * created by ZhangPan on 2024/4/24
 */
class InfoViewGroupManager : ViewGroupManager<InfoViewGroup>() {
    override fun getName(): String {
        return "NativeInfoViewGroup"
    }

    override fun createViewInstance(context: ThemedReactContext): InfoViewGroup {
        return InfoViewGroup(context)
    }
}

DemoReactPackager.kt

package com.awesomeproject.rn

import com.awesomeproject.viewManager.InfoViewGroupManager
import com.awesomeproject.viewManager.InfoViewManager
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager

/**
 *
 * created by ZhangPan on 2024/4/22
 */
class DemoReactPackager : ReactPackage {
    override fun createNativeModules(context: ReactApplicationContext): MutableList<NativeModule> {
        return mutableListOf<NativeModule>().apply {
            add(AppModule(context))
        }
    }

    override fun createViewManagers(context: ReactApplicationContext): MutableList<ViewManager<*, *>> {
        val mutableListOf = mutableListOf<ViewManager<*, *>>()
        mutableListOf.add(InfoViewManager())
        mutableListOf.add(InfoViewGroupManager())
        return mutableListOf
    }
}
  1. 在JS层导入原生组件,并封装导出JS模块

NativeInfoViewGroup.tsx

import { useEffect, useRef } from "react";
import { StyleSheet, UIManager, ViewProps, findNodeHandle, requireNativeComponent } from "react-native"


type NativeInfoViewGroupType = ViewProps | {
    
}

const NativeInfoViewGroup =  requireNativeComponent<NativeInfoViewGroupType>('NativeInfoViewGroup');

export default (props : any) => {
    const { children } = props;

    return(
        <NativeInfoViewGroup 
            style={styles.inforViewGroup}
        >
            { children }
        </NativeInfoViewGroup>
    )
}

const styles = StyleSheet.create({
    inforViewGroup: {
        width:'100%',
        height: '100%'
    }
})

NativePage.tsx

import { Button, NativeModules, StyleSheet, View } from 'react-native'
import NativeInfoView from './NativeInfoView';
import NativeInfoViewGroup from './NativeInfoViewGroup';

export default () => {
    return(
        <View style={styles.root}>
            <Button 
                title='调用原生方法'
                onPress={() => {
                    const { App } = NativeModules;
                    // App?.openGallery() 
                    // App?.getVersionName().then((data: string) => {
                    //     console.log(data)
                    // })
                    const { VersionName, VersionCode } = App;
                    console.log(`VersionNmae: ${VersionName}, VersionCode: ${VersionCode}`)
                }}
            />
            {/* <NativeInfoView /> */}
            <NativeInfoViewGroup>
                <View style={styles.view}></View>
            </NativeInfoViewGroup>
        </View>
    );

}

const styles = StyleSheet.create({
    root: {
        "width": '100%',
        "height": '100%',
    },
    view: {
        width: 100,
        height: 100,
        backgroundColor: 'red'
    },
})
  1. 属性、方法回调、api调用和ViewManager一致
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,185评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,445评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,684评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,564评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,681评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,874评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,025评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,761评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,217评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,545评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,694评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,351评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,988评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,778评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,007评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,427评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,580评论 2 349

推荐阅读更多精彩内容