React知识整理-类型校验PropTypes
冰洋 1/12/2020 React
react从入门到放弃
# 为什么使用prop-type
对组件入参props的校验
# 学习文档
# 具体使用
- 要在组件的 props 上进行类型检查,你只需配置特定的 propTypes 属性
- 您可以通过配置特定的 defaultProps 属性来定义 props 的默认值:
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
interface PersonProps {
name?: string;
age?: number,
gender?: 'male' | 'female',
hobby?: Array<string>,
position?: { x: number, y: number },
friends?: Array<{ name: string, age: number }>,
[prop: string]: any
}
let root: HTMLElement | null = document.getElementById('root');
class Person extends React.Component<PersonProps> {
static defaultProps: PersonProps = {
name: 'Stranger'
}
static propTypes = {
name: PropTypes.string.isRequired,
gender: PropTypes.oneOf(['male', 'female']),
hobby: PropTypes.arrayOf(PropTypes.string),
position: PropTypes.shape({
x: PropTypes.number,
y: PropTypes.number
}),
age(props: PersonProps, propName: string, componentName: string) {
let age = props[propName];
if (age < 0 || age > 120) {
return new Error(`Invalid Prop ${propName} supplied to ${componentName}`)
}
},
friends: PropTypes.arrayOf((propValue: any, key: string, componentName: string, location: string, propFullName: string): Error | null => {
console.log('propValue=' + JSON.stringify(propValue, null, 2), "key=" + key, "componentName=" + componentName, "location=" + location, "propFullName=" + propFullName);
/**
* propValue=[{ name: 'zhangsan', age: 10 }, { name: 'lisi', age: -20 }] key=0 componentName=Person location=prop propFullName=friends[0]
* propValue=[{ name: 'zhangsan', age: 10 }, { name: 'lisi', age: -20 }] key=1 componentName=Person location=prop propFullName=friends[1]
*/
let age = propValue[key].age;
if (age < 0 || age > 120) {
return new Error(
'Invalid prop `' + propFullName + '.age` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
return null;
})
}
render() {
let { name, age, gender, hobby, position } = this.props;
return (
<table>
<thead>
<tr>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
<td>爱好</td>
<td>位置</td>
</tr>
</thead>
<tbody>
<tr>
<td>{name}</td>
<td>{age}</td>
<td>{gender}</td>
<td>{hobby!.join(',')}</td>
<td>{position!.x + ' ' + position!.y}</td>
</tr>
</tbody>
</table>
)
}
}
let personProps: PersonProps = {
age: 80,
gender: 'male',
hobby: ['basketball', 'football'],
position: { x: 10, y: 10 },
friends: [{ name: 'zhangsan', age: 10 }, { name: 'lisi', age: -20 }]
}
ReactDOM.render(<Person {...personProps} />, root);
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81