抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

defaultProps 和 prop-types

使用 defaultProps 设置组件的默认值

React 中,使用静态的 defaultProps 属性,来设置组件的默认属性值。

格式举例:

1
2
3
4
5
// 在 React 中,使用静态的 defaultProps 属性,来设置组件的默认属性值
static defaultProps = {
initcount: 0 // 如果外界没有传递 initcount,那么,自己初始化一个数值(比如0)
};

使用prop-types进行props数据类型的校验

在组件中,可以通过 prop-types 把外界传递过来的属性,做类型校验。如果类型不匹配,控制台会弹出告警。

注意:如果要为 传递过来的属性做类型校验,必须安装 React 提供的 第三方包,叫做 prop-types

格式举例:

1
2
3
static propTypes = {
initcount: ReactTypes.number // 使用 prop-types 包,来定义 initcount 为 number 类型
};

下方代码中,在引用组件的时候,如果类型不匹配:

1
2
3
4
5
6
7
8
9
// 使用 render 函数渲染 虚拟DOM
ReactDOM.render(
<div>
{/* 规定,每个用户在使用 组件的时候,必须传递一个 默认的 数值,作为 组件初始化的 数据 */}
<Counter initcount="我是string类型"></Counter>
</div>,
document.getElementById("app")
);

控制台告警如下:

20190212_2130.png

代码举例

我们把 defaultPropsprop-types 来举个例子。

(1)index.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head></