``` import React, { Component } from 'react' import PropTypes from 'prop-types'; export default class DataTypeAttribute extends Component { // 配置props默认值 static defaultProps = { is: false } // ----------------------------------------------------------------------- // 调用相应的函数进行验证 // PropTypes.any -- 数组类型 // PropTypes.bool -- 布尔值 // PropTypes.func -- 函数类型 // PropTypes.number -- 数字类型 // PropTypes.object -- 对象类型 // PropTypes.string -- 字符串类型 // PropTypes.symbol -- 符号类型 // PropTypes.node -- 任何可以被渲染的内容(string、number、react元素、) // PropTypes.element -- React元素 // PropTypes.elementType -- React元素类型 // PropTYpes.instanceOf(构造函数) -- 必须是制定构造函数的实例 // PropTypes.oneOf([xxx,xxx]) -- 枚举(需要传递该数组中包含的值'xxx') // PropTypes.oneOfType([PropTypes.string,PropTypes.number,PropTypes.xxx]) -- 传递的类型必须是数组中的其中一种 // PropTypes.arrayOf(PropTypes.xxx) -- 必须是某一类型组成的数组、(必须传递数组类型,并且约束数组中的每一项必须是string/number等类型) PropTypes.arrayOf(PropTypes.number) // PropTypes.objectOf(PropTypes.xxx) -- 对象由某一类型的值组成 // PropTypes.shape({ // 更加具体的约束、 // name: PropTypes.string.isRequired, // age: PropTypees.number // address: PropTypes.shape({xxx:PropTypes.string}).isRequired // 表示这个对象必填 // }) // PropTypes.arrayOf(PropTypes.shape({name:PropTypes.string, age:PropTypes.number})) // 数组中的每一项必须为object,并且约束每一项的属性 // PropTypes.exact({...}); // 同PropTypes.shape一样。对象必须精确匹配传递的数据 // ----------------------------------------------------------------------- // 校验props属性 static propTypes = { // isRequired -- 必填 // bool -- Boolean is: PropTypes.bool.isRequired, a: PropTypes.number.isRequired, b: PropTypes.any, c: PropTypes.node, // ... // 自定义校验规则 score: function (props, propName, componentName) { console.log(props, propName, componentName); const val = props[propName]; if (typeof val === 'number' && (val >= 0 && val <= 100)) { return; } else { return new Error(propName + ' 该属性必须是一个数字,并且取值范围是0~100。'); } } } render() { return ( <div> {this.props.score} </div> ) } } ```