图标字体
您可以使用Icon 组件。 https://material-ui.com/components/icons/#icon-font-icons
要使用图标,只需将图标名称(字体连字)与 Icon 组件包装起来,例如:
import Icon from '@material-ui/core/Icon';
<Icon>star</Icon>
https://codesandbox.io/s/material-demo-forked-sj66h?file=/demo.tsx
假设您使用适当的图标连字设置菜单项:
const menuItems = [
{ label: "Home", path: "/home", icon: "home" },
{ label: "Accounts", path: "/accounts", icon: "account_circle" },
{ label: "Organizations", path: "/organizations", icon: "settings" }
];
然后你可以映射它们:
{menuItems.map(({ label, icon }) => {
return (
<span key={label}>
{label} <Icon>{icon}</Icon>
</span>
);
})}
SVG 图标
如果您想使用 SVG 图标而不是基本图标,我建议您只提取您计划使用的 SVG 图标,以便从生成的捆绑包中对您不使用的图标进行树状抖动。摇树的能力是使用 SVG 图标而不是字体图标的一个很好的理由。
import { Home, AccountCircle, Settings, AddCircle } from "@material-ui/icons";
如果您想允许用户输入所有图标或事先不知道将显示哪些图标,您可以从@material-ui/icons 导入所有内容,如Jonathan's answer。
如果您没有将图标列表放入需要能够被字符串化的东西(即 Redux/通过 API 调用发送),那么您可以直接将图标放入数组并渲染它们:
const menuItems: MenuItem[] = [
{ label: "Home", path: "/home", icon: <Home /> },
{ label: "Accounts", path: "/accounts", icon: <AccountCircle /> },
{ label: "Organizations", path: "/organizations", icon: <Settings /> }
];
// Rendering:
{menuItems.map(({ label, icon }) => {
return (
<span key={label}>
{label} {icon}
</span>
);
})}
如果您要将图标放在需要字符串化的地方,上述方法将不起作用,因此我建议将您要使用的图标放入对象中以映射它们。这样你就有一个字符串到图标映射。
示例:https://codesandbox.io/s/material-icons-svg-udcv3?file=/demo.tsx
import { Home, AccountCircle, Settings, AddCircle } from "@material-ui/icons";
const icons = {
Home,
AccountCircle,
Settings
};
在上面的例子中(即从数组中渲染图标)
interface MenuItem {
label: string;
path: string;
icon: keyof typeof icons;
}
const menuItems: MenuItem[] = [
{ label: "Home", path: "/home", icon: "Home" },
{ label: "Accounts", path: "/accounts", icon: "AccountCircle" },
{ label: "Organizations", path: "/organizations", icon: "Settings" }
];
// Rendering:
{menuItems.map(({ label, icon }) => {
const Icon = icons[icon];
return (
<span key={label}>
{label} <Icon />
</span>
);
})}