React Native 系列(六) -- PropTypes

前言

本系列是基于React Native版本号0.44.3写的。在我们之前的通过props实现组件间传值的时候,大家有没有发现在父组件传递值过去,在子控件获取props的时候没有提示,那么如何能实现让其有提示呢?这篇文章将带领大家去认识一下PropTypes这个玩意。

PropTypes

  • 问题: 在自定义组件的时候,通常需要暴露属性出去,并且设置属性类型,外界在使用自定义组件的属性的时候,需要有自动提示属性功能。

  • 解决: 使用PropTypes

  • PropTypes用处:

    • 可以实现类型检查,当传入错误的属性值,会报警告,但是不会报错
    • PropTypes定义属性,外界使用的时候会有提示
  • 注意点:

    • PropTypes必须要用static声明,否则无效果
    • PropTypes只能用于React框架的自定义组件,默认JS是没有的,因为它是React框架中的。
  • static:用来定义类方法或者类属性,定义类的方法和属性,生成的对象就自动有这样的属性了。

PropTypes的使用

  • PropTypes:属性检测,使用的时候需要先导入,在React框架中
import React, { Component, PropTypes } from 'react';
  • 使用

在自定义组件添加如下代码:

static propTypes = {
    name: PropTypes.string,
    age: PropTypes.number
}
  • 效果:
    图1

属性类型

// 数组类型
PropTypes.array

// 布尔类型
PropTypes.bool

// 函数类型
PropTypes.func

// 数值类型
PropTypes.number

// 对象类型
PropTypes.object

// 字符串类型
PropTypes.string

// 规定prop为必传字段
PropTypes.(类型).isRequired

// prop为任意类型
PropTypes.any.isRequired

给自定义属性设置初始值

  • 如果想要给自定义属性添加默认初始值,需要使用defaultProps
  • 注意:也是需要用static修饰
static defaultProps = {
    name: 'scottDefault',
    age: 12
}

实战演练

class ScottComponent extends Component {
    static propTypes = {
        name: PropTypes.string.isRequired,
        age: PropTypes.number
    }

    static defaultProps = {
        name: 'scottDefault',
        age: 12
    }

    render(){
        return (
            <View style={styles.scottStyle}>
                <Text>组件名字:{this.props.name}</Text>
                <Text>组件年龄:{this.props.age}</Text>
            </View>
        );
    }
}

// 主组件
export default class RNDemoOne extends Component {
  render() {
    return (
        <View style={styles.container}>
            <ScottComponent/>
        </View>
    );
  }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },

    scottStyle: {
        flex: 1,
        backgroundColor: '#F5FCFF',
        justifyContent: 'center',
        alignItems: 'center',
    },
});

致谢

如果发现有错误的地方,欢迎各位指出,谢谢!

原文地址:https://www.cnblogs.com/scott-mr/p/7340067.html