prop-types包
yarn add prop-types -S
index.jsx
import React, { Component } from 'react'
import Child from './Child'
import { Abc } from './Abc'
const abc = new Abc()
class Index extends Component {
state = {
count: 0,
}
render() {
return (
<>
<Child title={new Abc()}>
<div>abc</div>
<div>def</div>
</Child>
</>
);
}
}
export default Index;
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
Child.jsx
import React, { Component } from 'react'
import {
string,
node,
element,
elementType,
instanceOf,
oneOf,
oneOfType,
number,
arrayOf,
shape,
exact
} from 'prop-types'
import { Abc } from './Abc'
class Child extends Component {
static defaultProps = {
title: 'default props value'
}
static propTypes = {
title: node //数字、字符串、元素或包含这些类型的数组(或片段)。
//title:element//react元素<MyComponent />
//title:elementType//react元素类型MyComponent
//title: instanceOf(Abc) //是否是Abc的实例
// title: oneOf(['aaa', 'bbb']) //'aaa','bbb'中的第一个
// title: oneOfType([//String类型和number类型中的一种
// string,
// number
// ])
// title: arrayOf(number)//number类型的数组
// title: shape({//传入的title参数有string类型的aaa和number类型的ddd
// aaa: string,//其中ddd是必须的,还可有别的属性
// ddd: number.isRequired
// }),
// title: exact({//精准匹配(和shape相比)
// abc: string,
// def: number.isRequired
// }),
// title(props, propName, componentName) {//对title进行自定义判断
// if (props.title.abc !== 'aaa') {//三个参数 属性 属性名 组件名
// throw new Error('你传的abc的值不正确')
// }
// }
}
render() {
return (
<div>
{this.props.children}
</div>
)
}
}
export default Child;
Abc.js
export class Abc {
render() {
return 'abc'
}
}
|