react进阶 react属性默认值和属性类型检查

属性默认值和类型检查

属性默认值

通过静态属性defaultProps告知 react 属性默认值

函数组件

混合属性默认值和属性传入值在调用函数之前完成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import React from "react";

export default function FunctionDefaultProps(props) {
return (
<div>
姓名:{props.name}, 年龄:{props.age}
</div>
);
}

FunctionDefaultProps.defaultProps = {
name: "xyq",
age: 21,
};

类组件

混合属性默认值和属性传入值在运行构造函数函数之前完成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React, { Component } from "react";

export default class ClassDefaultProps extends Component {
render() {
return (
<div>
名字:{this.props.name}
年龄:{this.props.age}
</div>
);
}
}

ClassDefaultProps.defaultProps = {
name: "xyq",
age: 21,
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React, { Component } from "react";

export default class ClassDefaultProps extends Component {
static defaultProps = {
name: "xyq",
age: 21,
};
render() {
return (
<div>
名字:{this.props.name}
年龄:{this.props.age}
</div>
);
}
}

类型检查

使用库:prop-type
对组件调用静态属性propTypes告知 react 如何检查属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

PropTypes.any://任意类型
PropTypes.array://数组类型
PropTypes.bool://布尔类型
PropTypes.func://函数类型
PropTypes.number://数字类型
PropTypes.object://对象类型
PropTypes.string://字符串类型
PropTypes.symbol://符号类型

PropTypes.node://任何可以被渲染的内容,字符串、数字、React元素
PropTypes.element://react元素
PropTypes.elementType://react元素类型
PropTypes.instanceOf(构造函数)://必须是指定构造函数的实例
PropTypes.oneOf([xxx, xxx])://枚举
PropTypes.oneOfType([xxx, xxx]); //属性类型必须是数组中的其中一个
PropTypes.arrayOf(PropTypes.XXX)://必须是某一类型组成的数组
PropTypes.objectOf(PropTypes.XXX)://对象由某一类型的值组成
PropTypes.shape(对象): //属性必须是对象,并且满足指定的对象要求,属性可以增加
PropTypes.exact({...})://对象必须精确匹配传递的数据,属性不能多

//自定义属性检查,如果有错误,返回错误对象即可
属性: function(props, propName, componentName) {
//...
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import React, { Component } from "react";
import PropTypes from "prop-types";
export default class PropTypeUse extends Component {
static propTypes = {
a: PropTypes.string, //必须是字符串
b: PropTypes.number.isRequired, //必须是数字,且为必填属性
c: PropTypes.bool, //必须是boolean值
d: PropTypes.node.isRequired, //必须是可以被渲染的内容
e: PropTypes.shape({
name: PropTypes.string, //必须是字符串
age: PropTypes.number, //必须是数字
sex: PropTypes.oneOf(["男", "女"]), //必须是男或女
}),
};
render() {
return <div>{this.props.a}</div>;
}
}