react批量引入svg圖標的方法
在批量引入之前,我們需要安裝一個包并配置到typescript.json文件中。
1. 安裝:
yarn add -D @type/webpack-env
2. 配置typescript.json
"compilerOptions": {
"types": ["@types/webpack-env"]
}批量引入處理并導出封裝組件
在src文件下新建一個icon文件,然后新建一個.tsx文件
注:這塊代碼可直接copy走
import Icon from '@ant-design/icons';
// 批量引入
const importAll = (requireContext: __WebpackModuleApi.RequireContext) => {
const requireAll = requireContext.keys().map(key => {
const name = key.replace(/\.\/(.*)\.\w+$/, '$1');
console.log(name, requireContext(key))
return { name, value: requireContext(key) };
})
return requireAll
}
let routeList: {name: string, value: string}[] = []
try {
routeList = importAll(require.context('../assets/icons', true, /\.svg$/))
} catch (error) {
console.log(error);
routeList = []
}
/**
*
* 導出圖標
*
*/
const IconFont = (props: {name: string, width?: string | number, className?: string}) => {
const ListItem = routeList.find(item => item.name === props.name)
return (
<Icon
component={() => (
<img
src={ListItem?.value}
alt=""
width={props.width || 16}
/>
)}
{...props}
/>
);
};
export {
IconFont
}使用方式:
// 引入圖標
import { IconFont } from '@/icons/sider_left_icon'
<IconFont
name='library'
width="23"
className={styles.library_button_icon}
/>注:我之所以能直接使用@去默認引入src下的所有文件,是因為我在typescript中配置path
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
},
"types": ["@types/webpack-env"]
},詳細了解@types/webpack-env,可點擊鏈接查看
到此這篇關于react批量引入svg圖標的文章就介紹到這了,更多相關react批量引入svg內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
react native實現(xiàn)往服務器上傳網(wǎng)絡圖片的實例
下面小編就為大家?guī)硪黄猺eact native實現(xiàn)往服務器上傳網(wǎng)絡圖片的實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
在React中使用reduce方法處理復雜的對象數(shù)據(jù)
你想了解的是在 React + TypeScript 環(huán)境下,如何用 reduce 方法處理結構更復雜的對象數(shù)據(jù)(而非簡單數(shù)組),我會通過分層拆解 + 實戰(zhàn)案例的方式,帶你掌握處理復雜對象數(shù)據(jù)的核心思2026-02-02
React Hooks - useContetx和useReducer的使用實例詳解
這篇文章主要介紹了React Hooks - useContetx和useReducer的基本使用,本文通過實例代碼給大家講解的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-11-11
React無限滾動插件react-infinite-scroll-component的配置優(yōu)化技巧
react-infinite-scroll-component是React無限滾動插件,簡化滾動加載邏輯,支持自定義提示和觸發(fā)距離,兼容移動端,體積小巧,適用于列表、聊天等場景,需結合虛擬滾動優(yōu)化性能,本文介紹React無限滾動插件react-infinite-scroll-component的配置+優(yōu)化,感興趣的朋友一起看看吧2025-09-09
React18系列reconciler從0實現(xiàn)過程詳解
這篇文章主要介紹了React18系列reconciler從0實現(xiàn)過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01

