如何在反应中渲染 svg 文件?

How to render svg file in react?

我想上传一个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;

您可以使用以下库来转换 svg。您还可以将其 cli 命令添加到您的 package.json

https://react-svgr.com/playground/