我有多个像这样的图标组件:
import { IconProps } from "@utils/types";
const FilterIcon = (props: IconProps) => {
const { fillColor, width, height } = props;
return (
<svg
width={width}
height={height}
viewBox="0 0 24 24"
fill="white"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M17.625 12C1..."
fill={fillColor}
/>
</svg>
);
};
export default FilterIcon;
问题是我在不同的文件中几乎有 40 个。我想制作一个组件以更好的方式使用它们,如下所示:
<Icon name="IconName" width="20px" height="20px" fillColor="white" />
其中名称可以是枚举类型或类似类型
我制作了一个巨大的 Icon 组件,导入所有图标并使用 switch 返回图标组件(130 行...)
首先,你可以声明一个桶文件:
// icons/index.ts
export { default as FilterIcon } from './FilterIcon.tsx'
// ...
然后创建一个
<Icon>
组件:
// icon.tsx
import * as icons from './icons'
export const Icon = ({ name, ...props }: {
name: keyof typeof icons,
// other props
}) => {
const Component = icons[name]
return <Component {...props} />
}