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)
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)
请注意图标名称是小写字母和下划线分隔
| 归档时间: |
|
| 查看次数: |
11155 次 |
| 最近记录: |