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;

效果图如下:

相关推荐
returnShitBoy13 分钟前
前端面试:React hooks 调用是可以写在 if 语句里面吗?
前端·javascript·react.js
love黄甜心13 分钟前
Sass:深度解析与实战应用
前端·css·sass
goto_w1 小时前
使用elementplus的table表格遇到的问题
前端·javascript·vue.js
Moment1 小时前
如果你想找国外远程,首先让我先给你推荐这几个流行的技术栈 🤪🤪🤪
前端·后端·github
浪裡遊1 小时前
利用github部署项目
前端·github·持续部署
烂蜻蜓2 小时前
HTML 颜色名:网页色彩世界的基石
前端·css·html·html5
匹马夕阳2 小时前
Vite项目中vite.config.js中为什么只能使用process.env,无法使用import.meta.env?
开发语言·前端·javascript
只有一斤了呐2 小时前
超硬核!教你手搓一套船新架构的前端脚手架~
前端·javascript·开源
拉不动的猪2 小时前
刷刷题38(前端实现分包及组件懒加载的核心方案&&图片懒加载)
前端·javascript·面试
任磊abc2 小时前
在react当中利用IntersectionObserve实现下拉加载数据
前端·react·observer·下拉加载·intersection