目录
一、props类型校验基础
1、安装属性校验包:npm add prop-types
2、导入prop-types
3、使用
示例
import React from "react";
// 里面有各种内置的校验规则
import PropTypes from 'prop-types';
function TestComponent ({list}) {
return (
<div>
子组件
{list.map((item,index) => <div key={index}>{item}</div>)}
</div>
)
}
// 这里的propTypes首字母要小写,其他的大写
TestComponent.propTypes = {
// 定义各种规则
list: PropTypes.array //限定这里list的类型为数组
}
class App extends React.Component{
render() {
return (
<div className="App">
<TestComponent list={5} />
</div>
);
}
}
export default App;
这里如果传的不是数组类型就会报以下错误:意思是期待一个array类型但传过来的是一个number类型,发生错误的属性名为TestComponent
将list改为数组类型就可以了
import React from "react";
// 里面有各种内置的校验规则
import PropTypes from 'prop-types';
function TestComponent ({list}) {
return (
<div>
子组件
{list.map((item,index) => <div key={index}>{item}</div>)}
</div>
)
}
TestComponent.propTypes = {
// 定义各种规则
list: PropTypes.array //限定这里list的类型为数组
}
class App extends React.Component{
render() {
return (
<div className="App">
<TestComponent list={[1,2,3,4,5]} />
</div>
);
}
}
export default App;
二、props校验规则说明
可前往官方查询
https://legacy.reactjs.org/docs/typechecking-with-proptypes.html
常用类型:array、bool、func、number、object、string
// 常用类型
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
// PropTypes.定义类型.isRequired
requiredFunc: PropTypes.func.isRequired //必填项
三、props校验默认值
1、使用defaultProps
若test的值没有传递,那么显示的就是'默认值',若传了就以传递的数据为准
import React from "react";
// 里面有各种内置的校验规则
import PropTypes from 'prop-types';
function TestComponent (props) {
return (
<div>
子组件
<div>{props.test}</div>
</div>
)
}
// 函数组件默认值
TestComponent.defaultProps = {
test: '默认值'
}
class App extends React.Component{
render() {
return (
<div className="App">
{/* <TestComponent /> */}
<TestComponent test={'传递的数据'} />
</div>
);
}
}
export default App;
2、使用函数参数默认值(推荐使用)
function TestComponent ({test= '默认值'}) {
return (
<div>
子组件
<div>{test}</div>
</div>
)
}
两者区别:
第一种在用的时候组件内部已经有了test这个prop
第二种只有在传递的时候组件内部才有这个prop
四、类组件默认值
1、与函数组件一样使用defaultProps
class TestComponent extends React.Component{
render() {
return (
<div>
子组件
</div>
)
}
}
TestComponent.defaultProps = {
test: '默认值'
}
2、使用类静态属性定义(推荐使用)
class TestComponent extends React.Component{
static defaultProps = {
test: '默认的值'
}
render() {
return (
<div>
子组件
{this.props.test}
</div>
)
}
}