简体   繁体   English

如何在 React 中渲染 svg 文件?

[英]How to render svg file in react?

I want to upload a svg file and show preview in react, but I don't know how to convert a svg file into react component.我想上传一个 svg 文件并在 React 中显示预览,但我不知道如何将一个 svg 文件转换为 React 组件。 I try to use DOMParser to parse svg-xml string to Dodument Object, but it is not working.我尝试使用DOMParser将 svg-xml 字符串解析为 Dodument Object,但它不起作用。

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;

You can use following library to convert svg's.您可以使用以下库来转换 svg。 You can also add its cli commands to your package.json您还可以将其 cli 命令添加到您的 package.json

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM