将 SVG 文件解析为 React 组件 [英] Parse SVG file to React component

查看:30
本文介绍了将 SVG 文件解析为 React 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 SVG 文件:check.svg

I have an SVG file: check.svg

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 28.3 28.3"><path d="M25.2 3.638l-1.6 1.6c-4.3 4.3-8.9 9.2-13.2 13.6l-5.9-4.9-1.7-1.4-2.8 3.3 1.7 1.4 7.5 6.2 1.6 1.3 1.4-1.4c4.8-4.8 9.9-10.4 14.6-15l1.6-1.6-3.2-3.1z"/></svg>

我想要一个 React 组件;但我不想要任何包装标签,只是

I want a React component from it; but I don't want any wrapper tag, just

<svg>
    <path […]/>
</svg>

我知道我可以做类似的事情

I know I can do something like

const renderSvg = svg => React.createElement('svg', {
  dangerouslySetInnerHTML: { __html: svg }
});

甚至更容易

const RenderSvg = (svg) => <svg dangerouslySetInnerHTML={{ __html: svg }} />;

但我最终会得到:

<svg>
  <svg>
    <path […]/>
  </svg>
</svg>

有谁知道如何在不使用外部库的情况下实现这一目标?

Does anyone know how to achieve this without using an external library?

推荐答案

将 SVG 放在一个单独的文件中,而不是 导入作为一个组件,像这样:

Have your SVG in a separate file, than import that as a component, like this:

import {ReactComponent as Circle} from "./circle.svg"

以下是一个演示 沙盒

这篇关于将 SVG 文件解析为 React 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆