一、props规则校验
- 安装 prop-types 包
$ npm install prop-types
- 导入 propTypes 对象
import propTypes from 'prop-types';
- 组件名.propTypes = {} 设置组件 传参规则
Comp.propTypes = {
param: propTypes.array // Comp组件 的 param 参数必须是 数组类型
}
示例:
import React from 'react';
import PropTypes from "prop-types";
function Son({list}) {
return (
<div>
{list.map(item => <p key={item}>{item}</p>)}
</div>
)
}
Son.PropTypes={
list: PropTypes.array
}
class App extends React.Component {
render() {
return (
<div>
<Son list="我企鹅亲子装"/>
</div>
)
}
}
export default App;
报错提示如下:
规则说明
参见https://zh-hans.reactjs.org/docs/typechecking-with-proptypes.html 四种常见结构
- 常用类型:
array 、number 、bool 、string 、func 、object 、symbol - React元素类型:
element - 必填项:
isRequired - 特定的结构对象:
shape({})
核心代码:
optionalFun: PropTypes.fun;
requiredFun: PropTypes.fun.isRequired;
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
}),
二、props默认值
1.函数式默认值
1.1 函数参数默认值 (新版推荐)
示例:
import React from "react";
function Son1({defaultTime = 10}) {
return (
<div>The timer is : {defaultTime}</div>
)
}
class App extends React.Component {
render() {
return (
<div>
<Son1 />
</div>
)
}
}
export default App;
1.2 defaultProps 设置默认值
function Son2({defaultTime}) {
return (
<div>The second timer is: {defaultTime}</div>
)
}
Son2.defaultProps = {
defaultTime: 100
}
class App extends React.Component {
render() {
return (
<div>
<Son1 />
<Son2 />
</div>
)
}
}
2.类式默认值
2.1 defaultProps
class Son3 extends React.Component {
render() {
return (
<div>The defaultTimer is : {this.props.defaultTime}</div>
)
}
}
Son3.defaultProps = {
defaultTime: 3333
}
2.2 类静态属性声明
class Son4 extends React.Component {
static defaultProps ={
defaultTime: 66666
}
render() {
return (
<div>The defaultTimer is : {this.props.defaultTime}</div>
)
}
}
完整示例
import { func } from "prop-types";
import React from "react";
function Son1({defaultTime = 10}) {
return (
<div>The timer is : {defaultTime}</div>
)
}
function Son2({defaultTime}) {
return (
<div>The second timer is: {defaultTime}</div>
)
}
Son2.defaultProps = {
defaultTime: 100
}
class Son3 extends React.Component {
render() {
return (
<div>The defaultTimer is : {this.props.defaultTime}</div>
)
}
}
Son3.defaultProps = {
defaultTime: 3333
}
class Son4 extends React.Component {
static defaultProps ={
defaultTime: 66666
}
render() {
return (
<div>The defaultTimer is : {this.props.defaultTime}</div>
)
}
}
class App extends React.Component {
render() {
return (
<div>
<Son1 />
<Son2 />
<Son3 />
<Son4 />
</div>
)
}
}
export default App;
如图:
|