[英]Can a default value be used in a proptype shape?
Is it possible to define a type for an object's with a required key value pair and a default key value pair?是否可以为具有所需键值对和默认键值对的对象定义类型?
Example:例子:
const myComponent = (props) => {
const {
myObject: {
someRequiredString,
someNotRequiredString,
}
}
}
myComponent.propTypes = {
myObject: PropTypes.shape({
someRequiredString.string.isRequired,
}).isRequired,
}
myComponent.defaultProps = {
myObject: {
someNotRequiredString: '',
}
}
So if i understand you correct, you need non-required object bit if this object exist it's must have 2 required field, and maybe one non-required所以如果我理解你是正确的,如果这个对象存在,你需要非必需的对象位,它必须有 2 个必填字段,也许一个非必需字段
So here we are:所以我们在这里:
componentForUser.propTypes = {
myObject: PropTypes.shape({
name:PropTypes.string.isRequired,
secondName:PropTypes.string.isRequired,
age:PropTypes.string,
}),
}
componentForUser.defaultProps = {
myObject: {
name: 'defaultName',
secondName: 'defaultSecondName',
age:21
}
}
In this case if User object is not required, instead of this you will get User with properties:在这种情况下,如果不需要 User 对象,您将获得具有属性的 User:
myObject: { name: 'defaultName', secondName: 'defaultSecondName', age:21 }
But if from props you will get object User without name, you catch Warning about required name and secondName.但是,如果从 props 中您将获得没有名称的对象 User,则会收到有关所需名称和第二个名称的警告。
也许自从提出这个问题以来这已经改变了,但是你不能为这样的嵌套值提供 defaultProps 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.