React Native自定义View(Android侧)

一、实现自定义View

kotlin 复制代码
@SuppressLint("SetTextI18n")
class BlankPlaceholder(context: Context): FrameLayout(context) {

    init {
        addView(
            TextView(context).apply {
                setTextColor(Color.WHITE)
                text = "I am blank placeholder"
                gravity = Gravity.CENTER
            },
            LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT
            )
        )
    }

}

二、实现并注册自定义的SimpleViewManager

实现SimpleViewManager用于封装自定义View并提供属性方法

kotlin 复制代码
class BlankPlaceholderViewManager: SimpleViewManager<View>() {

    override fun createViewInstance(reactContext: ThemedReactContext): View {
        return BlankPlaceholder(reactContext).apply {
            setBackgroundColor(Color.RED)
        }
    }

    override fun getName(): String = "BlankPlaceholder"

    @ReactProp(name = "bgColor")
    fun setPlaceholderBg(view: View, color: String) {
        view.setBackgroundColor(color.toColorInt())
    }
}

实现ReactPackage,用于暴露原生模块或者原生View

kotlin 复制代码
class CustomNativePackage: ReactPackage {
    override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
        return emptyList()
    }

    override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<in Nothing, in Nothing>> {
        return arrayListOf(
            BlankPlaceholderViewManager()
        )
    }
}

向注册ReactNativeHost注册ReactPackage

kotlin 复制代码
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(CustomNativePackage())
          }

      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
    }

三、在React Native中使用

根据设置的名称读取ViewManager并暴露给其他模块文件使用

js 复制代码
import { requireNativeComponent } from "react-native";

const BlankPlaceholder = requireNativeComponent('BlankPlaceholder');

export default BlankPlaceholder;

示例代码如下

js 复制代码
import { SafeAreaView, StatusBar, StyleSheet, Text } from "react-native";
import BlankPlaceholder from "../components/BlankPlaceholder";

const InitPage = () => {
    const name = "EANAM"
    return (
        <SafeAreaView style={styles.container}>
            <Text style={styles.centerText}>Hello, {name}</Text>
            <BlankPlaceholder style={styles.placeholder} bgColor={'green'}/>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        width: '100%',
        height: '100%',
        paddingTop: StatusBar.currentHeight,
        flexDirection: 'column'
    },  
    centerText: {
        textAlign: 'center'
    },
    placeholder: {
        width: '100%',
        height: 100,
    }
})

export default InitPage;

效果图如下:

相关推荐
Moment9 小时前
Vibe Coding 时代,到底该选什么样的工具来提升效率❓❓❓
前端·后端·github
IT_陈寒10 小时前
SpringBoot性能飙升200%?这5个隐藏配置你必须知道!
前端·人工智能·后端
小时前端11 小时前
React性能优化的完整方法论,附赠大厂面试通关技巧
前端·react.js
Nicko11 小时前
Jetpack Compose BOM 2026.02.01 解读与升级指南
前端
小蜜蜂dry12 小时前
nestjs学习 - 控制器、提供者、模块
前端·node.js·nestjs
优秀稳妥的JiaJi12 小时前
基于腾讯地图实现电子围栏绘制与校验
前端·vue.js·前端框架
前端开发呀12 小时前
从 qiankun(乾坤) 迁移到 Module Federation(模块联邦),对MF只能说相见恨晚!
前端
没想好d12 小时前
通用管理后台组件库-10-表单组件
前端
恋猫de小郭12 小时前
你用的 Claude 可能是虚假 Claude ,论文数据告诉你,Shadow API 中的欺骗性模型声明
前端·人工智能·ai编程
_Eleven13 小时前
Pinia vs Vuex 深度解析与完整实战指南
前端·javascript·vue.js