如何使用它的snake_case名称(React,material-ui)动态加载图标 [英] How can I dynamically load an icon using its snake_case name (React, material-ui)

查看:222
本文介绍了如何使用它的snake_case名称(React,material-ui)动态加载图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我会按照Material-ui的说明直接导入 .

Normally I'd use material-ui icons by importing them directly per the material-ui instructions.

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

But I have a text tag, which is the actual icon name (like calendar_view_day) and need to get and render an icon component from it dynamically.

我该怎么办:

render() {
  return (
    <Icon name="calendar_view_day" color="primary" />
  )
}

代替:

render() {
  return (
    <CalendarViewDay color="primary" />  // Imported by name
  )
}

推荐答案

好的,所以我对此大为思索.

OK, so I massively overthought this.

结果material-ui包括一个图标组件,该组件可让您执行此操作...并且它本身会转换名称,因此可以接受蛇,帕斯卡和其他变体. 注意,这将极大地增加捆绑包的大小,如评论中所指出.如果束大小受限制,则必须采取其他方法从某个位置提供图标SVG!

Turns out material-ui includes an icon component that allows you to do this... and it converts names itself, so accepts snake, pascal and other variants. BEWARE this will massively increase bundle size, as pointed out in the comments. If you're bundle size constrained, you'll have to take a different approach of serving the icon SVGs from somewhere!

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

...

render() {
  return (
    <Icon>{props.iconName}</Icon>
  )
}

先前的答案(有效但过度的矫over过正)

创建函数以用于

Previous answer (working but massive overkill)

Create function to:

...然后使用material-ui图标组件.

...Then use the material-ui Icon component.

代码如下:

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>
  )
}

这篇关于如何使用它的snake_case名称(React,material-ui)动态加载图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆