简体   繁体   English

使用 svg 作为反应组件

[英]using svg as react component

im trying to use SVG with react, but i can ti tried some solution, result i didn't find why i get this error:我试图使用 SVG 与反应,但我可以尝试一些解决方案,结果我没有找到为什么我得到这个错误:

InvalidCharacterError
Failed to execute 'createElement' on 'Document': The tag name provided ('<svg>
<g transform="translate(0.000000,227.000000) scale(0.100000,-0.100000)"
fill="#000000" stroke="none">
<

if there anyone who can help me i will be very thankful.如果有人可以帮助我,我将非常感激。 example of the code in codesandbox: https://codesandbox.io/s/svg-in-react-r3g6l?file=/index.js codesandbox 中的代码示例: https://codesandbox.io/s/svg-in-react-r3g6l?file=/index.js

This is what I usually do:这是我通常做的:

Visit https://react-svgr.com/playground/ and paste in your SVG and it will transform the SVG into React component.访问https://react-svgr.com/playground/并粘贴到您的 SVG 中,它会将 SVG 转换为 React 组件。 It lets you pass SVG attributes as props.它允许您将 SVG 属性作为道具传递。

You may check out its original library - svgr for other usages.您可以查看其原始库 - svgr以了解其他用途。

you should use the img tag你应该使用 img 标签

import Logo from "./Logo.svg
<img src={Logo} alt="Logo" />

"As part of features added to the new version of create-react-app (v2), we can now import SVGs as React components." “作为新版 create-react-app (v2) 新增功能的一部分,我们现在可以将 SVG 导入为 React 组件。”

Check this article for more options: using-svg-icons-components-in-react查看这篇文章以获取更多选项: using-svg-icons-components-in-react

*Edit: to change the color of the svg, use the 'fill' propery in CSS. *编辑:要更改 svg 的颜色,请使用 CSS 中的“填充”属性。 You can add id or class inside your svg to select it.您可以在 svg 中将 id 或 class 添加到 select 中。

fill: red;

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

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