根据组件需要或不需要道具重用常见的 PropType 形状
Reusing a common PropType shape with props required or not required depending on the component
我有一个通用的 proptype(在一个库中),多个组件导入和使用。
ListPropType = PropTypes.shape({
name: PropTypes.string,
creatorId: PropTypes.string.isRequired,
...
});
1) 对于某些组件,我想将名称设为必需,而对于某些组件,我不想。
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
函数的参数来进一步抽象它。
我有一个通用的 proptype(在一个库中),多个组件导入和使用。
ListPropType = PropTypes.shape({
name: PropTypes.string,
creatorId: PropTypes.string.isRequired,
...
});
1) 对于某些组件,我想将名称设为必需,而对于某些组件,我不想。
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
函数的参数来进一步抽象它。