我有一个通用的 proptype(在一个库中),多个组件导入和使用。ListPropType = PropTypes.shape({ name: PropTypes.string, creatorId: PropTypes.string.isRequired, ...});1) 对于某些组件,我想让名称成为必需的,而对于某些组件,我不想。2)另外,对于一些组件,我想在形状中添加额外的道具。是否有一种简单或通用的方法来处理这些用例,而不涉及复制所有内容,但不同的字段?
1 回答
慕斯王
TA贡献1864条经验 获得超2个赞
从来不必这样做,但我想您可以编写一个工厂方法来生成形状,这样您就可以isRequired即时添加到字段中。
const getShape = (requiredFields, extraFields) => {
const template = {
name: PropTypes.string,
creatorId: PropTypes.string.isRequired,
};
Object.keys(template).forEach(key => {
if (requiredFields.includes(key)) {
template[key] = template[key].isRequired;
}
});
return PropTypes.shape({
...template,
...extraFields,
});
}
// Create propType with 'name' required and extra date field
ListPropType = getShape(
['name'],
{ date: PropTypes.string }
);
您甚至可以通过将起始模板作为getShape函数的参数来进一步抽象。
添加回答
举报
0/150
提交
取消