默认情况下不支持命名空间标记

在尝试将 svg 作为 React Component 下载时,出现以下错误。

默认情况下不支持命名空间标记。React 的 JSX 不支持名称空间标记。您可以打开“ throwIfNamespace”标志来绕过此警告。

import React from "react";
import { ReactComponent as LO } from "../a/Logo.svg"
import { NavLink } from "react-router-dom";


const Logo = () => (
<>
<NavLink to={"/"}>
<LO width={"40px"} height={"40px"} />
</NavLink>
</>
);


export default Logo;

原因是什么?

80390 次浏览

In the SVG file, try changing:

    sketch:type TO sketchType
xmlns:xlink TO xmlnsXlink
xlink:href  TO xlinkHref

etc...

The idea is to create camelCase property, remember that you are working with JSX, you are not creating a string as XML does.

Since we are in the JSX playground your SVG tags should be written as camelCase

So you can easily optimize your SVG using the link below to avoid this error :)

svgminify

I recommend using svgo to compress your SVG files. Simple CLI tool that runs with NodeJS and doesn't require you to upload your copyrighted SVGs anywhere.

I had the same issue with all my svg files. Opening them in Adobe Illustrator and saving them again solved the issue.

The most simple solution is to just convert the SVG file to JSX.Then create a separate component or just copy paste the tag. This website does the job perfectly.

https://svg2jsx.com/

This is a nice tool that converts an SVG into a react friendly component and includes support for typescript

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

In mine I had to change:

   xmlns:svg="http://www.w3.org/2000/svg"

to

   xmlnsSvg="http://www.w3.org/2000/svg"