DMa*_*yer 58 reactjs react-proptypes
PropTypes.objectOf
和之间有什么区别PropTypes.shape
?在文档中:
// An object with property values of a certain type
optionalObjectOf: PropTypes.objectOf(PropTypes.number)
Run Code Online (Sandbox Code Playgroud)
VS
// An object taking on a particular shape
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
})
Run Code Online (Sandbox Code Playgroud)
我objectOf
应该何时使用,何时使用shape
?
djf*_*dev 103
PropTypes.objectOf
在描述属性类型相同的对象时使用.
const objectOfProp = {
latitude: 37.331706,
longitude: -122.030783
}
// PropTypes.objectOf(PropTypes.number)
Run Code Online (Sandbox Code Playgroud)
PropTypes.shape
在描述其键提前已知的对象时使用,并且可以表示不同的类型.
const shapeProp = {
name: 'Jane',
age: 25
}
// PropTypes.shape({ name: PropTypes.string, age: PropTypes.number })
Run Code Online (Sandbox Code Playgroud)
Lev*_*ler 35
只是想给出一个给出以下对象的例子:
{
petStore: {
animals: {
'23': { name: 'Snuffles', type: 'dog', age 13 }
'29': { name: 'Mittens', type: 'cat', age: 7 }
}
}
}
Run Code Online (Sandbox Code Playgroud)
ObjectOf和Shape
当对象可以具有不同的属性名称但每个属性的一组一致属性时使用:
const animalItemShape = {
name: PropTypes.string,
type: PropTypes.string,
age: PropTypes.number
}
const petStoreShape = {
animals: PropTypes.objectOf(PropTypes.shape(animalItemShape))
}
Run Code Online (Sandbox Code Playgroud)
如您所见,animals
是一个由多个属性组成的对象,每个属性都符合该animalItemShape
类型.
希望能帮助到你!
归档时间: |
|
查看次数: |
25935 次 |
最近记录: |