经常遇到需要PropTypes验证的时候,忘记了这个值该是什么,不得不去查一遍React官网,我想还是先记下来好了。所有属性都遵从驼峰命名,因此如果只有一个单词,那么他就是小写的。

布尔值 bool

1
bool: PropTypes.bool

函数 function

1
func: PropTypes.func

数字, 包括 int 和 float

1
number: PropTypes.number

字符串 string

1
string: PropTypes.string

函数 function

1
func: PropTypes.func

React元素 element

包括我们自己写的各种React component, 以及常见的 {this.props.children}

1
element: PropTypes.element

数组 Array

1
array: PropTypes.array

数组 Array, 指定每个元素类型

1
2
// 指定数组中的元素类型为 number
array: PropTypes.arrayOf(PropTypes.number)

对象 object

1
obj: PropTypes.object

对象 object, 指定每个值的类型

1
2
// 指定该对象的值为number
obj: PropTypes.objectOf(PropTypes.number)

对象 object, 指定对象结构

1
2
3
4
5
6
7
8
9
10
/*
object: {
name: 'name',
password: 'password'
}
*/

obj: PropTypes.shape({
name: PropTypes.string,
name: PropTypes.string
})

同时指定多种类型

1
2
3
4
5

oneOfTypes: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
])

还可以限定属性的值

1
2
// 限定enum的值只能为'news' 或者 'photos'
enum: PropTypes.oneOf(['news', 'photos'])

自定义对象

也可以在已有对象(class)的基础上,指定某PropTypes的值为该class的实例(instance)

1
2
// import Message from ',somewhere/Message'
classInstance: PropTypes.instanceOf(Message)

自定义验证规则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 如果验证失败,应该直接"return" 一个 Error对象,不是”throw", 也不是 "console.error()"
* @param
props 当前调用者所传入的所有属性和值的键值对
* @param
propName 当前验证的属性名,此处为'custom'
@param
componentName 当前component的名称,也即是定义本属性的对象
**/

custom: function (props, propName, componentName) {
// 如果传入的属性中,属性'custom'的值不包括 ’matchme' , 则返回’验证失败‘
if (!/matchme/.test(props[propName])) {
return new Error('Validation failed!');
}
}