我正在嘗試在目標檔案中獲取 SVG。然后像這樣使用SVG。
import {CustomIcons} from "./Icons"
<CustomIcons name="FrameIcon" />
<CustomIcons name="VectorIcon" />
我只想匯入一個檔案并根據名稱獲取自定義圖示。我已經嘗試了幾個小時,但我迷路了
自定義圖示.tsx
export const CustomIcons = {
FrameIcon: (
<svg
width="632"
height="330"
viewBox="0 0 632 330"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C695.409 238.987 667.885 262.248 636.416 276.436C612.104 287.397 589.793 302.386 564.742 311.911C523.785 327.491"
fill="#232323"
/>
</svg>
),
VectorIcon: (
<svg
width="632"
height="330"
viewBox="0 0 632 330"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C69"
fill="#232323"
/>
</svg>
),
};
uj5u.com熱心網友回復:
我在這里看到了幾個問題,我會盡可能多地解釋:
- 匯出值的型別(例如 FrameIcon)應該是一個函式 例如,您的檔案應該以這種方式匯出:
export {
FrameIcon: () => (
<svg
width="632"
height="330"
viewBox="0 0 632 330"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C695.409 238.987 667.885 262.248 636.416 276.436C612.104 287.397 589.793 302.386 564.742 311.911C523.785 327.491"
fill="#232323"
/>
</svg>
),
VectorIcon: () => (
<svg
width="632"
height="330"
viewBox="0 0 632 330"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C69"
fill="#232323"
/>
</svg>
),
};
- 匯入應該是:
import { FrameIcon } from './Icons'
額外小費
創建一個名為 Icon 的檔案夾,在其中創建以下檔案:
index.jsFrameIcon.jsxVectorIcon.jsx
您index.js應該匯出在此檔案夾中創建的所有圖示,例如:
export * from './FrameIcon';
export * from './VectorIcon';
你FrameIcon的例子應該是:
const FrameIcon = () => (
<svg
width="632"
height="330"
viewBox="0 0 632 330"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C695.409 238.987 667.885 262.248 636.416 276.436C612.104 287.397 589.793 302.386 564.742 311.911C523.785 327.491"
fill="#232323"
/>
</svg>
)
export { FrameIcon };
我希望這有幫助。
uj5u.com熱心網友回復:
您應該將 CustomIcons 定義為功能組件
像這樣的東西應該作業
import React from 'react';
const CustomIcons = (props) => {
const icons = {
FrameIcon :
<svg width="632" height="330" viewBox="0 0 632 330" fill="none" xmlns="http://www.w3.org/2000/svg" >
<path d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C695.409 238.987 667.885 262.248 636.416 276.436C612.104 287.397 589.793 302.386 564.742 311.911C523.785 327.491" fill="#232323"/>
</svg>,
VectorIcon:
<svg width="632" height="330" viewBox="0 0 632 330" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C69" fill="#232323"/>
</svg>
}
return <>
{icons[props.name]}
</>
};
export default CustomIcons;
`
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/459429.html
標籤:javascript 反应 打字稿 svg 图标
上一篇:如何在SVG上模擬文本選擇行為
