正如上面对thclark回答的评论中所述,使用 Icon 组件的解决方案将使用 Material-UI 图标的字体版本,它不包含完整的图标集。
通过使用相同的方法来获得正确的图标名称(从thclark借来),并结合 React.createElement 来解决这个问题。我在 TypeScript 中做到了这一点,在 vanilla javascript 中更容易。这是 TS 版本 (dynamicIcon.tsx) 中的组件,也可在此 repo 中找到:
import * as React from 'react';
import * as Icons from '@material-ui/icons/';
type IconType = typeof import('@material-ui/icons/index');
interface DynamicIconProps {
iconName: string,
className: string
}
function upperFirst(string:string) {
return string.slice(0, 1).toUpperCase() + string.slice(1, string.length)
}
function fixIconNames(string: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;
}
export default class DynamicIcon extends React.Component<DynamicIconProps> {
constructor(props: DynamicIconProps) {
super(props);
}
render() {
return React.createElement(Icons[fixIconNames(this.props.iconName)! as keyof IconType], {className: this.props.className});
}
}