我想上傳一個 svg 檔案并在 react 中顯示預覽,但我不知道如何將 svg 檔案轉換為 react 組件。我嘗試使用DOMParser將 svg-xml 字串決議為 Dodument 物件,但它不起作用。
import { useState } from 'react';
import { Upload, Button, Card } from 'antd';
import { UploadChangeParam } from 'antd/lib/upload/interface';
import 'antd/dist/antd.css';
function App() {
const [svgs, setSvgs] = useState<Document[]>([]);
const handleChange = async ({ file }: UploadChangeParam) => {
console.log(file);
let domparser = new DOMParser();
const svg = (await file.originFileObj?.text()) ?? '';
const ele = domparser.parseFromString(svg, 'image/svg xml');
setSvgs([...svgs, ele]);
};
return (
<div style={{ margin: 50 }}>
<Upload name="file" showUploadList={false} onChange={handleChange}>
<Button>Upload</Button>
</Upload>
{/* preview list */}
<Card style={{ marginTop: 20 }}>
{svgs.map((SVGComponent) => {
return <SVGComponent />;
})}
</Card>
</div>
);
}
export default App;
uj5u.com熱心網友回復:
您可以使用以下庫來轉換 svg。您還可以將其 cli 命令添加到您的 package.json
https://react-svgr.com/playground/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465891.html
標籤:javascript 反应 svg
