橋接原生

為什么需要橋接原生

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

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

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

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層調(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. 實現(xiàn)一個原生自定義組件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注冊到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="美國總統(tǒng)"
        />
    )
}

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

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

InfoView.kt 做了一個點擊事件,然后回調(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這個方法:

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="美國總統(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="美國總統(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. 實現(xiàn)一個原生容器組件

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,注冊行為和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='調(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)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容