Since JavaScript is a dynamically typed language, we don’t really have a way to enforce the type of a variable at compile time, and if we pass invalid types, they will fail at runtime or give weird results if the types are compatible but not what we expect.
由于JavaScript是一种动态类型的语言,因此我们实际上没有办法在编译时强制使用变量的类型,并且如果我们传递无效的类型,则它们将在运行时失败,或者如果类型兼容则给出奇怪的结果,但是我们的期望。
Flow and TypeScript help a lot, but React has a way to directly help with props types, and even before running the code, our tools (editors, linters) can detect when we are passing the wrong values:
Flow和TypeScript有很多帮助,但是React可以直接帮助props类型,甚至在运行代码之前,我们的工具(编辑器,lints)也可以检测到何时传递了错误的值:
import PropTypes from 'prop-types'
import React from 'react'
class BlogPostExcerpt extends Component {
render() {
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.props.description}</p>
</div>
)
}
}
BlogPostExcerpt.propTypes = {
title: PropTypes.string,
description: PropTypes.string
}
export default BlogPostExcerpt
我们可以使用哪些类型 (Which types can we use)
These are the fundamental types we can accept:
这些是我们可以接受的基本类型:
- PropTypes.array PropTypes.array
- PropTypes.bool PropTypes.bool
- PropTypes.func PropTypes.func
- PropTypes.number PropTypes.number
- PropTypes.object PropTypes.object
- PropTypes.string PropTypes.string
- PropTypes.symbol PropTypes.symbol
We can accept one of two types:
我们可以接受以下两种类型之一:
PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),
We can accept one of many values:
我们可以接受许多值之一:
PropTypes.oneOf(['Test1', 'Test2']),
We can accept an instance of a class:
我们可以接受一个类的实例:
PropTypes.instanceOf(Something)
We can accept any React node:
我们可以接受任何React节点:
PropTypes.node
or even any type at all:
甚至根本没有任何类型:
PropTypes.any
Arrays have a special syntax that we can use to accept an array of a particular type:
数组具有一种特殊的语法,我们可以使用它来接受特定类型的数组:
PropTypes.arrayOf(PropTypes.string)
Objects, we can compose an object properties by using
对象,我们可以使用
PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
})
要求属性 (Requiring properties)
Appending isRequired
to any PropTypes option will cause React to return an error if that property is missing:
附加isRequired
任何PropTypes选项将导致作出React,如果该属性是缺少返回一个错误:
PropTypes.arrayOf(PropTypes.string).isRequired,
PropTypes.string.isRequired,