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;

效果图如下:

相关推荐
妙码生花43 分钟前
PHP 各框架下和 Go 的性能比较
前端·后端·go
Csvn1 小时前
TypeScript 类型性能:让类型体操不再卡死编译器
前端
万少1 小时前
等不到 Apple 的折叠 iPhone,我用 DeepV4.1Flash + workBuddy 一句话自己造了一台
前端·javascript·后端
梦曦i1 小时前
uni-router v0.2.0重磅发布:全链路拦截+重复导航优化
前端·uni-app
数据知道1 小时前
AES 加密实战——模式选择(ECB/CBC/GCM)与安全陷阱
前端·网络·安全
一夜枫林2 小时前
vue实现scroll-view上下滑动右侧左右滑动
前端·javascript·vue.js
苏三的开发日记2 小时前
npm EPERM:无法写入 `.npmrc` 的排查与解决
前端
YWL2 小时前
OpenLayers地图分享:URL参数同步+分享链接生成,让用户一键分享地图视角
前端·javascript·vue·openlayers
枫叶梨花2 小时前
Electrobun透明窗口在Windows上的输入穿透排查
前端·electron·bun
云上工程笔记4 小时前
AstraFlow + React/Vite:如何用自然语言开发并部署一个 AI 咖啡网站原型
前端·人工智能·react.js