reactjs - 反应可能缺少属性的对象的proptype数组
问题描述
我有一个肯定是一组对象的道具。对象可以或不可以具有许多这样的属性。
columns: [
{name: 'name' //is always required },
{name: 'security_group_rules' , display: "Rules" },
{name: 'revision_number' , display: "revision number" , sortable:true },
]
如何编写对象部分来验证属性是值还是未定义
我想过用这种方式写它,但它看起来很奇怪
columns : PropTypes.arrayOf(
PropTypes.shape({
name : PropType.string.isRequired,
display : PropTypes.oneOfType ([PropType.string, undefined])
sortable : PropTypes.oneOfType ([PropType.bool, undefined])
})
).isRequired
解决方案
This question looks similar with this post. Take a look.
You can apply defaultProps on those optional properties.
MyComponent.defaultProps = {
columns: [{
display: undefined,
sortable: undefined
}];
};
MyComponent.propTypes = {
columns: PropTypes.arrayOf(
PropTypes.shape({
name: PropType.string.isRequired,
display: PropType.string,
sortable: PropType.bool
})
).isRequired,
...
}
推荐阅读
- python - Qt(PyQt)事件循环中的xmlprc?
- scala - 如何使用 Slick 在 SQLite 中启用外键验证
- javascript - 如何在流中设置动态反应类变量
- java - 如何打印出具有字母集和长度的可能字符串?
- qt - 如何通过 qsslsocket 实现 ftp over tls 客户端?
- arrays - 按 MongoDb 中的深层文档字段排序
- sql - 选择带有通配符的列?
- macos - 为这个刽子手游戏添加一个功能
- go - 在 kubernetes 中使用 go 提取服务的 clusterIP
- angular - 我如何在 chrome 扩展中插入谷歌标签管理器以弹出窗口?