createFromIconfontCN 可以把 iconfont 的图标,包装成组件,支持本地导入和在线导入。
每一个 icon 组件就是一个 svg,控制他大小的属性是 font-size
在线导入
typescript
const IconFont = createFromIconfontCN({
scriptUrl: "//at.alicdn.com/t/font_131235b87iudi.js",
});本地导入
把 iconfont 上的 js 下载下来,命名为: iconfont.js,放入本地目录的 public 文件夹。
typescript
const IconFont = createFromIconfontCN({
scriptUrl: "iconfont.js",
});使用图标
导入成功后,想使用图标,只需要引用组件,填入 iconfont 上图标对应的标签,就可以成功渲染出 Icon
typescript
import { IconFont } from "@/components/iconfont";
function App() {
return <IconFont type="icon-menu" />;
}获取所有图标
有时候,我们可能想根据iconfont提供的文件,获取其中的图标集合,去做一些图标选择组件。对于iconfont.js,可以使用正则表达式去解析。
javascript
//scriptUrl 可以自己自定义
const scriptUrl = import.meta.env.VITE_ICONFONT_URL ?? "iconfont.js";
const { data: icons } = useQuery({
queryKey: ["get-icon"],
queryFn: async () => {
return axios.get(scriptUrl);
},
select: (res) => {
if (res.data && typeof res.data === "string") {
const matchs = res?.data?.match(/(icon-[a-zA-Z_\-0-9]+)/g);
return matchs;
}
return [];
},
refetchOnWindowFocus: false,
});