admin管理员组文章数量:1418410
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: '',
}
}
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: '',
}
}
Share
Improve this question
asked Aug 13, 2019 at 11:32
RemiRemi
5,36713 gold badges60 silver badges94 bronze badges
2
- 1 Usually required field didn't have a default value – Vadim Hulevich Commented Aug 13, 2019 at 11:37
- True, but how about an object which has both a required and not required field? @VadimHulevich – Remi Commented Aug 13, 2019 at 12:47
2 Answers
Reset to default 4So 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
So here we are:
ponentForUser.propTypes = {
myObject: PropTypes.shape({
name:PropTypes.string.isRequired,
secondName:PropTypes.string.isRequired,
age:PropTypes.string,
}),
}
ponentForUser.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:
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.
Maybe this has changed since this question was asked, but you can't provide defaultProps for a nested value like this.
本文标签: javascriptCan a default value be used in a proptype shapeStack Overflow
版权声明:本文标题:javascript - Can a default value be used in a proptype shape? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745273817a2651056.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论