props参数类型限定
实现步骤
- 安装属性校验包:
npm install prop-types - 导入
prop-types包 - 使用
组件名.propTypes = {}给组件添加校验规则
父组件
import List from "./components/List"
const App = () => {
const list = [
{ id: 1, name: '吃饭' },
{ id: 2, name: '睡觉' },
{ id: 3, name: '打豆豆' }
]
return (
<div>
<h2>列表</h2>
<List list={list} />
</div>
)
}
export default App
子组件
import PropTypes from "prop-types";
const List = (props) => {
const arr = props.list
const lists = arr.map((item, index) => <li key={index}>{item.name}</li>)
return (
<div>
<ul>
{lists}
</ul>
</div>
)
}
// 为组件添加校验规则
List.propTypes = {
list: PropTypes.array
}
export default List
校验规则说明
- 常见类型:array、bool、func、number、object、string
- React元素类型:element
- 必填项:isRequired
- 特定的结构对象:shape({})
// 限定传值为函数
List.propTypes = {
fn: PropTypes.func
}
// 对一个参数限定为必传项,在后面写 isRequired
List.propTypes = {
fn: PropTypes.func.isRequired
}
// 特定结构的对象
// 父组件给子组件传值为对象,要包含name和age字段,类型也加上限定
List.propTypes = {
obj: PropTypes.shape({
name: PropTypes.string,
age: PropTypes.number
}).isRequired
}
官网文档更多阅读:reactjs.org/docs/typech…
props校验-默认值
通过 defaultProps 可以给组件的props设置默认值,在未传入props的时候生效
函数组件 - 直接使用函数参数默认值
function List({pageSize = 10}) {
return (
<div>
props的默认值:{ pageSize }
</div>
)
}
// 不传入pageSize属性
<List />
类组件 - 使用类静态属性声明默认值,static defaultProps = {}
class List extends Component {
static defaultProps = {
pageSize: 10
}
render() {
return (
<div>
props的默认值:{this.props.pageSize}
</div>
)
}
}
<List />