React中使用 PropTypes 进行类型检查
2024-09-06 14:17:26
官方文档学习链接:https://zh-hans.reactjs.org/docs/typechecking-with-proptypes.html
import React, { Component } from 'react'
import PropTypes from 'prop-types'
class TodoItem extends Component {
constructor (props) {
super(props)
this.handleClick = this.handleClick.bind(this)
}
render() {
const { content, test } = this.props
return (
<li onClick={this.handleClick}>
{ test } - { content }
{/* { this.props.content } */}
</li>
)
}
handleClick () {
const { deleteItem, index } = this.props
deleteItem(index)
// this.props.deleteItem(this.props.index)
}
}
// PropTypes规定父组件传递值的类型
TodoItem.propTypes = {
// isRequired 设置属性为必传
test: PropTypes.string.isRequired,
// oneOfType:一个对象可以是几种类型中的任意一个类型
content: PropTypes. oneOfType([PropTypes.number, PropTypes.string]),
// content: PropTypes.string,
deleteItem: PropTypes.func,
index: PropTypes.number
}
// 若父组件没有给子组件传值(test),可以通过defaultProps设置默认值
TodoItem.defaultProps = {
test: 'hello world'
}
export default TodoItem
最新文章
- 设计模式(十二):bridge模式
- 记录s标签范例
- python生成中文验证码,带旋转,带干扰噪音线段
- information_schema系列四(跟踪,列约束,表和列)
- 一些Android程序的反逆向方法
- Mssql显错和不显错模式下的注入
- 2017年开年的第一次比较大的安全事件: MongoDB “赎金事件”,如何看待互联网安全问题
- Ubuntu自带的vi编辑器太难用了,换
- hadoop部署错误
- 每天一个Linux命令(14)--head命令
- 记MSSQL数据库sa账号短时间密码失效问题
- JFile的导入xlsx与xls
- Docker镜像的实现原理
- Unity 用ml-agents机器学习造个游戏AI吧(1)(Windows环境配置)
- Qt QLabel 大小随内容自动变化 &;&; 内容填充整个label空间
- Canal学习笔记(服务端)
- linux实现自动检测进程是否存活的脚本
- Java主要版本平台
- Linux下的Jmeter运行测试
- JMeter 连接MySQL
热门文章
- Java入门 - 高级教程 - 05.网络编程
- 自建CDN Xnign产品指标
- 把本地仓库同步到github上去
- 论文翻译:Mastering the Game of Go without Human Knowledge (第一部分)
- 关于Windows Server 服务器 安装tomcat部署Java Web 项目的问题
- Spring相关jar说明
- 【原创】在 ASP.NET Core 3.1 中使用 Senparc.Weixin.Work 企业微信 SDK —— 发送文本消息
- linux启动Firefox报错,及解决方法
- 学过 C++ 的你,不得不知的这 10 条细节!
- Simscape Multibody 教程 —— 入门学习