我有一个使用大量 React 图标的 React 应用程序。我已经考虑过导入和使用它们的不同方法,但我不确定是否应该考虑对性能有任何重大影响。
1.在我的顶级App组件中导入我的所有图标,并根据需要将它们传递给每个组件。
这就是我现在正在做的事情,以为我只导入一次 SVG,但是将这些图标向下传递到更高阶和子组件变得很烦人。
import { ReactComponent as IconApartment } from './icons/material/apartment.svg';
import { ReactComponent as IconBookmark } from './icons/material/bookmark.svg';
import { ReactComponent as IconCalendarToday } from './icons/material/calendar-today.svg';
// etc.
const icons = {
apartment: <IconApartment />,
bookmark: <IconBookmark />,
calendar: <IconCalendar />,
};
return (
<MyComponent icons={icons} />
):
2. 我可以只在需要它们的每个组件中导入图标。
这是有道理的,但我担心很多组件使用相同的图标,并且为每个组件重复相同的导入似乎会适得其反。
我的组件
import { ReactComponent as IconApartment } from './icons/material/apartment.svg';
return (
<div>{<IconApartment />}</div>
);
我的其他组件
import { ReactComponent as IconApartment } from './icons/material/apartment.svg';
return (
<div>{<IconApartment />}</div>
);
3. 我可以做一个自定义的钩子。
它本质上会执行选项 1,但不是作为道具传递给子组件,我可以独立实例化它。
自定义挂钩
import { ReactComponent as IconApartment } from './icons/material/apartment.svg';
import { ReactComponent as IconBookmark } from './icons/material/bookmark.svg';
import { ReactComponent as IconCalendarToday } from './icons/material/calendar-today.svg';
// etc.
export function useIcons() {
const icons = {
apartment: <IconApartment />,
bookmark: <IconBookmark />,
calendar: <IconCalendar />,
};
return icons;
}
我的组件
import { useIcons } from './hooks.js';
const { icons } = useIcons();
return (
<div>{icons.apartment}</div>
);
--
什么是最高效的解决方案?最佳做法是什么?