问题
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>
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 }
});
or even easier
const RenderSvg = (svg) => <svg dangerouslySetInnerHTML={{ __html: svg }} />;
But I would end up with:
<svg>
<svg>
<path […]/>
</svg>
</svg>
Does anyone know how to achieve this without using an external library?
回答1:
Have your SVG in a separate file, than import that as a component, like this:
import {ReactComponent as Circle} from "./circle.svg"
Following is a demo sandbox
来源:https://stackoverflow.com/questions/60455670/parse-svg-file-to-react-component