我必须从v3升级到v4,以前我们常常显示字符串中的一些图标作为属性传递,如下所示:
<Icon type={props.icon} />有没有办法通过新的图标系统在antd v4中实现这样的功能呢?我知道'@ant-design/compatible'的存在,但是迁移是为了减少包的大小,所以我想避免使用这种解决方案。
编辑:我只是改变了我使用图标的方式,在我的配置文件中,我导入了图标,并像这样将它们传递给我的生成器:icon = {props.icon}而不是以前的<Icon type={props.icon} />。
发布于 2020-06-30 14:27:27
我使用@loadable/component并创建了一个传递类型的动态组件
文件DynamicIcon.js:
import loadable from "@loadable/component";
const DynamicIcon = loadable(props =>
import(`@ant-design/icons/es/icons/${props.type}.js`)
.catch(err => import(`@ant-design/icons/es/icons/WarningOutlined.js`)))
export default DynamicIcon;并像之前一样调用图标v3:
<DynamicIcon type={'TagOutlined'} />发布于 2020-06-05 23:26:29
const Icon = ({type, ...rest}) => {
const icons = require(`@ant-design/icons`);
const Component = icons[type];
return <Component {...rest}/>
}发布于 2020-10-14 16:13:02
我在这里找到一种动态加载菜单图标的方法。我不喜欢其他的解决方案。因此,我决定创建另一个解决方案。
我的解决方案很简单。实际上它不是动态的,它选择已经加载的组件。但这对Webpack来说是安全的,因为它只会在源代码中包含使用的组件。这意味着结果大小小于包含已发布文件夹中所有svg文件的700多个计数。
// IconSelector.tsx
import React from 'react';
import {
QuestionOutlined,
DashboardOutlined,
SmileOutlined,
FormOutlined,
TabletOutlined,
ProfileOutlined,
CheckCircleOutlined,
WarningOutlined,
UserOutlined,
HighlightOutlined,
TableOutlined,
} from '@ant-design/icons';
interface IconSelectorProps {
type: string;
}
const IconSelector: React.FC<IconSelectorProps> = (props: IconSelectorProps) => {
const Icons = {
QuestionOutlined: <QuestionOutlined />,
DashboardOutlined: <DashboardOutlined />,
SmileOutlined: <SmileOutlined />,
FormOutlined: <FormOutlined />,
TabletOutlined: <TabletOutlined />,
ProfileOutlined: <ProfileOutlined />,
CheckCircleOutlined: <CheckCircleOutlined />,
WarningOutlined: <WarningOutlined />,
UserOutlined: <UserOutlined />,
HighlightOutlined: <HighlightOutlined />,
TableOutlined: <TableOutlined />,
};
const getIcon = (type: string) => {
// Default Icon when not found
let comp = <QuestionOutlined />;
let typeNew = type;
// Default is Outlined when no theme was appended (ex: 'smile')
if (!typeNew.match(/.+(Outlined|Filled|TwoTone)$/i)) {
typeNew += 'Outlined';
}
// If found by key then return value which is component
const found = Object.entries(Icons).find(([k]) => k.toLowerCase() === typeNew.toLowerCase());
if (found) {
[, comp] = found;
}
return comp;
};
return getIcon(props.type);
};
export default IconSelector;<Menu.Item key="1" icon={menu.icon ? <IconSelector type={menu.icon} /> : null}>
Smile
</Menu>或
<Menu.Item key="1">
<IconSelector type="smile" />
<span>Smile</span>
</Menu>https://stackoverflow.com/questions/62218381
复制相似问题