ReactNative 封装控件的一点经验

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/j550341130/article/details/81698106

Demo请见我的github:
https://github.com/YouCii/RNDemo/tree/master/src/js/component

经常使用的布局封装成一个单独的控件是很常见的需求, 基本步骤如下:

  1. 创建控件(类似于一个Screen)

    import React, {Component} from 'react'
    ...
    export default class SettingItem extends Component {
        render() {
            return <View ...
        }
    }    
  2. 使用时直接用标签即可

    <SettingItem />

style样式传递

直接尝试上方代码时会发现在 <SettingItem /> 中定义的style样式并没有什么卵用, 这是因为style并没有在 SettingItem 类中被使用, 可以这样做:

    export default class SettingItem extends Component {
        render() {
            return <View 
            style={[{...InternalStyle...}, this.props.style]}>
                ...
            </View>
        }
    }   

这里把this.props.style作为了控件根View的Style中的一部分, 这样外部定义的style就会在空间内部生效了.
注意: style的定义规则是以后面定义的为准, 所以要把this.props.style放在内部style的后面, 以免某些样式被内部样式覆盖掉.


props传递

如果这个自定义的控件有多种样式/状态, 需要根据外部字段判断来确定, 可以这样做:

    export default class SettingItem extends Component {
        render() {
            return <View 
            style={[{...InternalStyle...}, this.props.style]}>
                ...
                {!this.props.showBottomDivider ? null : <NormalDivider/>}
                ...
            </View>
        }
    }
    SettingItem.defaultProps = {
        showBottomDivider: true
    };   
    <SettingItem
        showBottomDivider={false}
    />

注意, 这里的 showBottomDivider props属性不能作为控件内部的数据变化暂存对象, 直接代码修改此属性是无效的


props类型限制

在多人协同开发时有可能出现以下场景:
A写好了一个控件, 该控件中需要一个string类型的属性, B在使用此控件时并不知道必须传入此属性, 或者不知道此属性必须是string类型的, 这就会产生很多不必要的麻烦.

那RN里有没有像java里@Nullable @ColorInt 注解类似功能的机制呢? 答案是prop-types.
prop-types 原来是在源码中的, 后来被单独抽出作为一个库, 使用npm install --save prop-types安装它.

这样使用:

SettingItem.propTypes = {
    // showBottomDivider强制为布尔类型, isRequired则要求必须写入
    showBottomDivider: PropTypes.bool.isRequired, 
};

如果使用了isRequired, 没有定义该字段时会弹出警告; 另外在编码过程中, 会给予代码提示
这里写图片描述

更多功能请看: https://github.com/facebook/prop-types

猜你喜欢

转载自blog.csdn.net/j550341130/article/details/81698106