Component – React 中文文档
prop-types - npm (npmjs.com)
React.PropTypes已移入另一个包中。因此首先我们需要安装 prop-types 库。
npm install --save prop-types
主要用法:
- 常规校验
- 自定义校验
- 数组(对象)校验
- 插槽校验
- 属性默认值
- 节点、元素等其他校验
import ChildCom from "./components/ChildCom";function App() {return (<div className="App"><h1>我是 App</h1><ChildCom name={"jk-stu"} age={20} score={[11,22]} ><p>插入一些内容</p></ChildCom><ChildCom score={[11,22]} ><p>插入一些内容</p></ChildCom></div>);
}export default App;
import React from 'react';
import PropTypes from "prop-types";function ChildCom(props) {return (<div>这是子组件<div>姓名:{props.name} 年龄:{props.age}</div><div>{props.children}</div></div>);
}// props 类型校验
ChildCom.propTypes = {// name: PropTypes.string,age: PropTypes.number,/*** 自定义校验规则* @param props 组件的props* @param propName 校验的属性名* @param componentName 组件的名称* @returns {Error}*/name: function(props, propName, componentName) {if (!/-stu/.test(props[propName])) {return new Error('Invalid prop `' + propName + '` supplied to' +' `' + componentName + '`. Validation failed.');}},/*** 数组类型校验* @param propValue 校验的属性值* @param key 校验的属性值在数组中的位置* @param componentName 组件的名称* @param location 校验的属性名在组件中的位置* @param propFullName 校验的属性名在组件中的完整名称 比如 score[2]* @returns {Error}*/score: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {if (typeof propValue[key] !== 'number') {return new Error('Invalid prop `' + propFullName + '` supplied to' +' `' + componentName + '`. Validation failed.');}}),// 插槽校验 这里必须插入一个elementchildren: PropTypes.element.isRequired
}
// props 设置默认值
// 但该用法即将移除
ChildCom.defaultProps = {name: '张三-stu',age: 18
}export default ChildCom;