橋接原生

為什么需要橋接原生

實(shí)現(xiàn)react層JS實(shí)現(xiàn)不了的需求:

  1. 復(fù)雜、高性能組件:復(fù)雜表格逻锐、視頻播放等
  2. 原生層開發(fā)能力:傳感器編程、widget等
  3. 平臺(tái)屬性:系統(tǒng)信息、設(shè)備信息等
  4. 對(duì)接三方應(yīng)用:相機(jī)败砂、相冊(cè)、地圖等

橋接原生實(shí)現(xiàn)JS調(diào)用原生方法

1. 編寫并注冊(cè)原生層方法

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中注冊(cè)

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層調(diào)用原生方法

NativePage.tsx

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

export default () => {
    return(
        <View style={styles.root}>
            <Button 
                title='調(diào)用原生方法'
                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調(diào)用原生:

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

橋接原生原子組件

1. 實(shí)現(xiàn)一個(gè)原生自定義組件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. 創(chuàng)建ViewManager魏铅,用于接管原生自定義組件的屬性和行為昌犹,并把ViewManager注冊(cè)到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層導(dǎo)入原生組件沦零,并封裝導(dǎo)出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="美國(guó)總統(tǒng)"
        />
    )
}

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

5. 原生組件回調(diào)JS層方法

InfoView.kt 做了一個(gè)點(diǎn)擊事件祭隔,然后回調(diào)給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這個(gè)方法:

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="美國(guó)總統(tǒng)"
            onValueChanged={(e: any) => {
                console.log(e.nativeEvent.value)
            }}
        />
    )
}

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

6. 公共原生組件方法給JS層調(diào)用

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="美國(guó)總統(tǒng)"
            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. 實(shí)現(xiàn)一個(gè)原生容器組件

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. 創(chuàng)建ViewGroupManager,注冊(cè)行為和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層導(dǎo)入原生組件路操,并封裝導(dǎo)出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='調(diào)用原生方法'
                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. 屬性疾渴、方法回調(diào)、api調(diào)用和ViewManager一致
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末屯仗,一起剝皮案震驚了整個(gè)濱河市搞坝,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌魁袜,老刑警劉巖桩撮,帶你破解...
    沈念sama閱讀 207,248評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異峰弹,居然都是意外死亡店量,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,681評(píng)論 2 381
  • 文/潘曉璐 我一進(jìn)店門鞠呈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)融师,“玉大人,你說(shuō)我怎么就攤上這事蚁吝『当” “怎么了舀射?”我有些...
    開封第一講書人閱讀 153,443評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)怀伦。 經(jīng)常有香客問(wèn)我脆烟,道長(zhǎng),這世上最難降的妖魔是什么房待? 我笑而不...
    開封第一講書人閱讀 55,475評(píng)論 1 279
  • 正文 為了忘掉前任邢羔,我火速辦了婚禮,結(jié)果婚禮上吴攒,老公的妹妹穿的比我還像新娘张抄。我一直安慰自己,他們只是感情好洼怔,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,458評(píng)論 5 374
  • 文/花漫 我一把揭開白布署惯。 她就那樣靜靜地躺著,像睡著了一般镣隶。 火紅的嫁衣襯著肌膚如雪极谊。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,185評(píng)論 1 284
  • 那天安岂,我揣著相機(jī)與錄音轻猖,去河邊找鬼。 笑死域那,一個(gè)胖子當(dāng)著我的面吹牛咙边,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播次员,決...
    沈念sama閱讀 38,451評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼败许,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了淑蔚?” 一聲冷哼從身側(cè)響起市殷,我...
    開封第一講書人閱讀 37,112評(píng)論 0 261
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎刹衫,沒想到半個(gè)月后醋寝,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,609評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡带迟,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,083評(píng)論 2 325
  • 正文 我和宋清朗相戀三年音羞,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片仓犬。...
    茶點(diǎn)故事閱讀 38,163評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡嗅绰,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情办陷,我是刑警寧澤,帶...
    沈念sama閱讀 33,803評(píng)論 4 323
  • 正文 年R本政府宣布律歼,位于F島的核電站民镜,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏险毁。R本人自食惡果不足惜制圈,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,357評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望畔况。 院中可真熱鬧鲸鹦,春花似錦、人聲如沸跷跪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,357評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)吵瞻。三九已至葛菇,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間橡羞,已是汗流浹背眯停。 一陣腳步聲響...
    開封第一講書人閱讀 31,590評(píng)論 1 261
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留卿泽,地道東北人莺债。 一個(gè)月前我還...
    沈念sama閱讀 45,636評(píng)論 2 355
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像签夭,于是被迫代替她去往敵國(guó)和親齐邦。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,925評(píng)論 2 344

推薦閱讀更多精彩內(nèi)容