对于组件来说,props是外部传入的,无法保证组件使用者传入什么格式的数据,简单来说就是组件调用者可能不知道组件封装着需要什么样的数据,如果传入的数据不对,可能会导致程序异常,所以必须要对于props传入的数据类型进行校验。
安装校验包
npm i -S prop-types

# 在组件中导入
import PropTypes from 'prop-types'
# 函数组件
function App(){}
// 验证规则
App.propTypes = {
prop-name:PropTypes.string
}
# 类组件
class App extends Component{
// 类内部完成 检查
static propTypes = {
prop-name:PropTypes.string
}
}
² 约束类型
https://zh-hans.reactjs.org/docs/typechecking-with-proptypes.html#proptypes
- 类型: array、bool、func、number、object、string
- React元素类型:element
- 必填项:isRequired
- 特定结构的对象: shape({})
父组件
import React, { Component } from 'react'
import Cmp2fun from './pages/Cmp2fun'
import Cmp2class from './pages/Cmp2class'
export default class App extends Component {
render() {
return (
<div>
{/* props.children 获取组件内中的数据 插槽 slot */}
{/* <Cmp2fun a={1} b={2} /> */}
{/* 默认值 如要传入值,则传入的值为主,默认值为辅 */}
<Cmp2fun a={1} />
<Cmp2class a={1} b={2} />
</div>
)
}
}
函数组件
import React from 'react'; // 引入proptypes类型检查 import PropTypes from 'prop-types'; // 函数组件 const Cmp2fun = ({ a, b }) => { console.log(a + b); return ( <div> </div> ); } // 类型检查 Cmp2fun.propTypes = { a: PropTypes.number, b: PropTypes.number } // 默认值 Cmp2fun.defaultProps = { b: 1000 } export default Cmp2fun;
类组件
import React, { Component } from 'react'
// 引入proptypes类型检查
import PropTypes from 'prop-types';
export default class Cmp2class extends Component {
// 静态方法不能使用this 静态方法属于类的 调用 类.方法名/属性名
static propTypes = {
// 类型前面是数字且还是必须填写输入的
a: PropTypes.number.isRequired,
b: PropTypes.number
}
// 给props添加默认值
static defaultProps = {
b: 100
}
render() {
let { a, b } = this.props
console.log(a + b);
return (
<div>
</div>
)
}
}
// 类型检查
/* Cmp2class.propTypes = {
a: PropTypes.number,
b: PropTypes.number
} */
// export default Cmp2class