一、defaultProps默认值
在组件内部 有时 有一些数据必须存在 程序的正常运行依赖着这些数据 而这些数据需要外界传入
此时 即使用户并没有传递参数 组件内部也要提供默认值 以供程序的正常运行
因为用户若不传递数据 则程序可能会出问题
在React中 可以通过静态的defaultProps
属性来设置组件的默认值
比如:
import React from 'react';
export default class Hello extends React.Component
{
constructor(props)
{
super(props);
this.state={}
}
static defaultProps = {
count:0
}
render()
{
return <div>
<h3>{this.props.count}</h3>
</div>
}
}
(defaultProps名称必须完全一致 且必须为静态的)
这样 外界若不传入该值 则组件内部的值会被自动设为defaultProps定义的默认值
组件外部若传入了值 则会使用传入的值
二、prop-types类型校验
React还支持给props属性设置类型校验
当传入的该属性的类型不一致的时候 可以进行处理
若要进行类型校验 则必须安装React提供的类型校验包 名为prop-types
安装:
npm i prop-types -S
导入:
import ReactPropTypes from "prop-types"
然后在组件的内部进行配置:
(注:名称必须为propTypes 且必须为静态的)
static propTypes = {
count:ReactPropTypes.number // 使用prop-types包 定义count为number类型
}
完整代码:
import React from 'react';
import ReactPropTypes from "prop-types";// 提供常见的数据类型 用于类型校验
export default class Hello extends React.Component
{
constructor(props)
{
super(props);
this.state={}
}
static defaultProps = {
initCount:0
}
static propTypes = {
count:ReactPropTypes.number // 使用prop-types包 定义count为number类型
}
render()
{
return <div>
<h3>{this.props.count}</h3>
</div>
}
}