(三)、验证Props的类型
2023年9月3日
一、类型验证
在前端开发中类型验证是十分重要的,避免在传递错误的类型时出现
bug
现在大部分前端应用使用的都是
TypeScript
来进行验证使用
React
原生方式进行验证- 导入
prop-types
这个库来进行验证 prop-types
这个库是React
自带的不需要额外的安装
- 导入
import PropTypes from 'prop-types'
function Nav({title, content, likes, onLike, author, tags}) {
Nav.propsTypes = {
title: PropsTypes.string,
onLike: PropsTypes.func.isRequired,
author: PropsTypes.shape({
name: PropTypes.string.isRequired,
description: PropTypes.string.isRequired
}),
tags: PropTypes.array
}
return (
)
}
export default Nav
prop-types
类型解释
二、string
字符串类型number
数字类型func
函数类型shape
函数对象类型object
对象类型array
数组类型isRequired
必传类型
Loading...