反应 propTypes:objectOf 与形状? [英] React propTypes: objectOf vs shape?

查看:34
本文介绍了反应 propTypes:objectOf 与形状?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PropTypes.objectOfPropTypes.shape 有什么区别?在 PropTypes 中:

What's the difference between PropTypes.objectOf and PropTypes.shape? In the PropTypes:

// An object with property values of a certain type
optionalObjectOf: PropTypes.objectOf(PropTypes.number)

对比

// An object taking on a particular shape
optionalObjectWithShape: PropTypes.shape({
  color: PropTypes.string,
  fontSize: PropTypes.number
})

什么时候应该使用objectOf,什么时候应该使用shape?

When should I use objectOf and when should I use shape?

推荐答案

PropTypes.objectOf 用于描述属性都是相同类型的对象.

PropTypes.objectOf is used when describing an object whose properties are all the same type.

    const objectOfProp = {
        latitude: 37.331706,
        longitude: -122.030783
    }
    // PropTypes.objectOf(PropTypes.number)

PropTypes.shape 用于描述一个键值提前已知的对象,并且可能代表不同的类型.

PropTypes.shape is used when describing an object whose keys are known ahead of time, and may represent different types.

    const shapeProp = {
        name: 'Jane',
        age: 25
    }
    // PropTypes.shape({ name: PropTypes.string, age: PropTypes.number })

这篇关于反应 propTypes:objectOf 与形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆