如何使用其蛇形名称动态加载图标(React,material-ui)

thc*_*ark 11 icons reactjs material-design material-ui

通常我会根据 material-ui 说明直接导入它们来使用 material-ui 图标。

但我有一个文本标签,它是实际的图标名称(如calendar_view_day),需要从中动态获取和呈现图标组件。

我怎么能这样:

render() {
  return (
    <Icon name="calendar_view_day" color="primary" />
  )
}
Run Code Online (Sandbox Code Playgroud)

代替:

render() {
  return (
    <CalendarViewDay color="primary" />  // Imported by name
  )
}
Run Code Online (Sandbox Code Playgroud)

thc*_*ark 14

好的,所以我严重过度考虑了这一点。

正确答案

原来material-ui包含一个图标组件,允许您执行此操作...并且它自己转换名称,因此接受蛇、帕斯卡和其他变体。请注意,正如评论中指出的那样,这将大大增加捆绑包的大小。如果您的包大小受到限制,您将不得不采用不同的方法从某个地方提供图标 SVG!

import Icon from '@material-ui/core/Icon'

...

render() {
  return (
    <Icon>{props.iconName}</Icon>
  )
}
Run Code Online (Sandbox Code Playgroud)

以前的答案(有效但大量矫枉过正)

创建函数以:

...然后使用 material-ui Icon 组件。

这是代码:

import Icon from '@material-ui/core/Icon'

function upperFirst(string) {
  return string.slice(0, 1).toUpperCase() + string.slice(1, string.length)
}

function fixIconNames(string) {
  const name = string.split('_').map(upperFirst).join('')
  if (name === '3dRotation') {
    return 'ThreeDRotation'
  } else if (name === '4k') {
    return 'FourK'
  } else if (name === '360') {
    return 'ThreeSixty'
  }
  return name
}

...

render() {
  const iconName = fixIconNames(props.iconName)
  return (
    <Icon>{props.iconName}</Icon>
  )
}
Run Code Online (Sandbox Code Playgroud)

  • 从 _material-ui_ 导入整个 _Icon_ 模块将解决该功能,但会**爆炸**捆绑包!您可以通过 [React 官方指南](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 分析包大小 (3认同)
  • 此解决方案使用字体图标而不是 svg 图标。需要加载使用的字体。请参阅:https://material-ui.com/components/icons/#icon-font-icons (2认同)
  • “正确答案”只为我打印字符串 props.iconName,不显示实际的图标。 (2认同)
  • @jonasRosenvist,您还需要在代码中包含一些链接: &lt;link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /&gt; (2认同)

Suf*_*ari 5

MUI 5 开发人员在这里。

import * as Muicon from "@mui/icons-material";
const Icon = Muicon['SatelliteAlt']
<Icon fontSize="large" sx={{ px: 1 }}/>
Run Code Online (Sandbox Code Playgroud)

打字稿

import * as MUIcon from "@mui/icons-material";
interface IconProps {
   icon?: keyof typeof MUIcon;
}
const IconComp: React.FC<IconProps> = ({
  icon,
}) => {
    const Icon = icon && MUIcon[icon];
    return ({Icon && <Icon />})
}
Run Code Online (Sandbox Code Playgroud)


小智 2

伙计们,快到 2024 年了,请使用字体材质图标。超轻量:

npm install material-icons@latest
Run Code Online (Sandbox Code Playgroud)

在 JS 中导入(示例:在 NextJS 中的src/index.jsCreate React App 中、在 Vue CLI 中):src/_app.jssrc/main.js

npm install material-icons@latest
Run Code Online (Sandbox Code Playgroud)

在您的组件中:

import 'material-icons/iconfont/material-icons.css';
Run Code Online (Sandbox Code Playgroud)

请注意图标名称是小写字母和下划线分隔