如何使用React Component在UI中显示svg图标(.svg文件)?

Kam*_*aju 20 svg reactjs

我已经看到很多用于svg的库反应但是没有人给我如何在react组件中导入.svg,我看过代码讨论带来svg代码反应而不是使用.svg图标作为图像并显示它在UI中.

如果有方法可以嵌入图标,请告诉我.

Rom*_*man 54

由于某些原因,上述方法对我不起作用,在我按照建议添加之前,.default如下所示:

<div>
  <img src={require('../../mySvgImage.svg').default} alt='mySvgImage' />
</div>
Run Code Online (Sandbox Code Playgroud)


jan*_*ann 49

我想告诉你两种方式.

第一个只是简单导入所需的SVG.

import MyImageSvg from '../../path/to.svg';
Run Code Online (Sandbox Code Playgroud)

只记得使用一个加载器,例如Webpack:

 {
     test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
     include: [Path.join(__dirname, "src/assets")],
     loader: "file-loader?name=assets/[name].[ext]"
 }
Run Code Online (Sandbox Code Playgroud)

另一种(更优雅的方式)是你可以定义一个SVG图标精灵并使用一个组件来获取SVG的正确精灵.例如:

import React from "react";
import Icons from "../../assets/icons/icons.svg"; // Path to your icons.svg
import PropTypes from 'prop-types';

const Icon = ({ name, color, size }) => (
  <svg className={`icon icon-${name}`} fill={color} width={size} height={size}>
    <use xlinkHref={`${Icons}#icon-${name}`} />
  </svg>
);

Icon.propTypes = {
  name: PropTypes.string.isRequired,
  color: PropTypes.string,
  size: PropTypes.number
};

export default Icon;
Run Code Online (Sandbox Code Playgroud)

图标精灵(icons.svg)可以定义为:

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">

    <symbol id="icon-account-group" viewBox="0 0 512 512">
      <path d="m256 301l0-41c7-7 19-24 21-60 10-5 16-16 16-30 0-12-4-22-12-28 7-13 18-37 12-60-7-28-48-39-81-39-29 0-65 8-77 30-12-1-20 2-26 9-15 16-8 46-4 62 1 2 2 4 2 5l0 42c0 41 24 63 42 71l0 39c-8 3-17 7-26 10-56 20-104 37-112 64-11 31-11 102-11 105 0 6 5 11 11 11l384 0c6 0 10-5 10-11 0-3 0-74-10-105-11-31-69-48-139-74z m-235 168c1-20 3-66 10-88 5-16 57-35 99-50 12-4 23-8 34-12 4-2 7-6 7-10l0-54c0-4-3-9-8-10-1 0-35-12-35-54l0-42c0-3-1-5-2-11-2-8-9-34-2-41 3-4 11-3 15-2 6 1 11-2 13-8 3-13 29-22 60-22 31 0 57 9 60 22 5 17-6 37-11 48-3 6-5 10-5 14 0 5 5 10 11 10 3 0 5 6 5 11 0 4-2 11-5 11-6 0-11 4-11 10 0 43-16 55-16 55-3 2-5 6-5 9l0 54c0 4 2 8 7 10 51 19 125 41 132 62 8 22 9 68 10 88l-363 0z m480-94c-8-25-49-51-138-84l0-20c7-7 19-25 21-61 4-2 7-5 10-9 4-5 6-13 6-20 0-13-5-23-13-28 7-15 19-41 13-64-4-15-21-31-40-39-19-7-38-6-54 5-5 3-6 10-3 15 3 4 10 6 15 3 12-9 25-6 34-3 15 6 25 18 27 24 4 17-6 40-12 52-3 6-4 10-4 13 0 3 1 6 3 8 2 2 4 3 7 3 4 0 6 6 6 11 0 3-1 6-3 8-1 2-2 2-3 2-6 0-10 5-10 11 0 43-17 55-17 55-3 2-5 5-5 9l0 32c0 4 3 8 7 10 83 31 127 56 133 73 7 22 9 68 10 88l-43 0c-6 0-11 5-11 11 0 6 5 11 11 11l53 0c6 0 11-5 11-11 0-3 0-74-11-105z"/>
    </symbol>

    <symbol id="icon-arrow-down" viewBox="0 0 512 512">
      <path d="m508 109c-4-4-11-3-15 1l-237 269-237-269c-4-4-11-5-15-1-5 4-5 11-1 15l245 278c2 2 5 3 8 3 3 0 6-1 8-3l245-278c4-4 4-11-1-15z"/>
    </symbol>

    <symbol id="icon-arrow-left" viewBox="0 0 512 512">
      <path d="m133 256l269-237c4-4 5-11 1-15-4-5-11-5-15-1l-278 245c-2 2-3 5-3 8 0 3 1 6 3 8l278 245c2 2 4 3 7 3 3 0 6-1 8-4 4-4 3-11-1-15z"/>
    </symbol>

    <symbol id="icon-arrow-right" viewBox="0 0 512 512">
      <path d="m402 248l-278-245c-4-4-11-4-15 1-4 4-3 11 1 15l269 237-269 237c-4 4-5 11-1 15 2 3 5 4 8 4 3 0 5-1 7-3l278-245c2-2 3-5 3-8 0-3-1-6-3-8z"/>
    </symbol>
</svg>
Run Code Online (Sandbox Code Playgroud)

您可以在http://fontastic.me/上免费定义自己的图标精灵.

用法: <Icon name="arrow-down" color="#FFFFFF" size={35} />

并且可以添加一些简单的样式,以便在任何地方使用图标:

[class^="icon-"], [class*=" icon-"] {
    display: inline-block;
    vertical-align: middle;
}
Run Code Online (Sandbox Code Playgroud)

  • 您在这里使用 [SVG 片段](https://caniuse.com/#feat=svg-fragment),甚至没有提及这一点,这对答案至关重要。 (2认同)

Tsu*_*uni 33

如果您使用create-react-app 2.0,您现在可以这样做:

import { ReactComponent as YourSvg } from './your-svg.svg';
Run Code Online (Sandbox Code Playgroud)

然后像使用组件一样使用它:

const App = () => (
 <div>
   <YourSvg />
 </div>
);
Run Code Online (Sandbox Code Playgroud)

  • 请记住,“ReactComponent”名称不是可选的。 (27认同)
  • 嗯,直接对我不起作用。`元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:未定义。您可能忘记从定义的文件中导出组件,或者您可能混淆了默认导入和命名导入。 (12认同)
  • 这只适用于 create-react-app,导致它转换 svg 来反应组件,否则你应该使用其他解决方案 (4认同)
  • @Jaison我总是将其设置为“fill =“currentColor””,这允许您在代码中设置它的样式。 (3认同)
  • 另请注意,颜色更改支持“fill”属性,但请确保使用 SVG 设置默认填充属性,如 &lt;svg fill="#000"&gt;。 (2认同)

Moh*_*iya 20

在这里我找到了一个简单的解决方案,无需弹出,我们不需要安装其他依赖项,例如react-app-rewired. 因为如果你想使用 SVG 作为组件,我们需要更新create-react-app.

方法一:

import { ReactComponent as YourSvg } from './your-svg.svg';

const App = () => (
 <div>
   <YourSvg />
 </div>
);
Run Code Online (Sandbox Code Playgroud)

我们可以这样做,但只能create-react-app-2.0按照上面的答案进行。

方法二:

我们需要更新 的 webpack 配置create-react-app

  1. node_modules/react-scripts/config/webpack.config.js
  2. the line number 600

注意:在这里您将看到以下信息

import { ReactComponent as YourSvg } from './your-svg.svg';

const App = () => (
 <div>
   <YourSvg />
 </div>
);
Run Code Online (Sandbox Code Playgroud)
  1. 将以下行添加到上面的file-loader中。
            // "file" loader makes sure those assets get served by WebpackDevServer.
            // When you `import` an asset, you get its (virtual) filename.
            // In production, they would get copied to the `build` folder.
            // This loader doesn't use a "test" so it will catch all modules
            // that fall through the other loaders.
            {
              loader: require.resolve('file-loader'),
              // Exclude `js` files to keep "css" loader working as it injects
              // its runtime that would otherwise be processed through "file" loader.
              // Also exclude `html` and `json` extensions so they get processed
              // by webpacks internal loaders.
              exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
              options: {
                name: 'static/media/[name].[hash:8].[ext]',
              },
            },
            // ** STOP ** Are you adding a new loader?
            // Make sure to add the new loader(s) before the "file" loader.
Run Code Online (Sandbox Code Playgroud)

就是这样

如何在React组件中使用SVG?

import ChevronRight from '../../../assets/icons/feather/chevron-right.svg';

const Links = () => {
  return (
          <ChevronRight height={25} width={25} />    
      );
};

export default Links;
Run Code Online (Sandbox Code Playgroud)


Hem*_*ari 15

您也可以导入.svg.jpg.png.ttf,等文件,如:

  ReactDOM.render(
      <img src={require("./svg/kiwi.svg")}/>,
      document.getElementById('root')
  );
Run Code Online (Sandbox Code Playgroud)


小智 12

如果您在本地有 .svg 或图像。首先,您必须安装 svg 所需的加载器和图像的文件加载器。然后你必须先导入你的图标或图像,例如:

import logo from './logos/myLogo.svg' ;
import image from './images/myimage.png';

const temp = (
     <div>
         <img src={logo} />
         <img src={image} />
     </div>
);

ReactDOM.render(temp,document.getElementByID("app"));

Run Code Online (Sandbox Code Playgroud)

快乐编码:")

来自 react 网站的资源,经过多次搜索后为我工作:https : //create-react-app.dev/docs/adding-images-fonts-and-files/


Sri*_*mam 6

如果远程托管图像,您可以直接使用.svgimg标记的扩展名.

ReactDOM.render(
  <img src={"http://s.cdpn.io/3/kiwi.svg"}/>,
  document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)

这是小提琴:http://codepen.io/srinivasdamam-1471688843/pen/ZLNYdy?编辑= 0110

注意:如果您使用任何Web应用程序捆绑包(如Webpack),则需要具有相关的文件加载器.

  • 我尝试这样做,但看不到显示的图像,我有本地图标 (3认同)
  • 但它会添加带有img标签的文件,没有svg的属性 (2认同)

mat*_*dor 6

很难相信添加自定义图标是如此复杂。我找到了与上面发布的解决方案类似的解决方案,但对我来说,在添加 viewBox 信息之前我无法显示图标,该信息是我通过在文本编辑器中打开 SVG 直接获得的。

//customIcon.js

import React from "react";
import {ReactComponent as ImportedSVG} from "path/to/myIcon.svg";
import { SvgIcon } from '@material-ui/core';

function CustomIcon() {
 return(
  <SvgIcon component={ImportedSVG} viewBox="0 0 384 512"/>

)
}

export default CustomIcon;
Run Code Online (Sandbox Code Playgroud)

我还遇到了命名空间错误,必须按照这篇文章的建议清理 SVG 才能工作


San*_*ues 5

如果您想使用 SVG 文件作为 React 组件来执行自定义并且不使用 create-react-app,请执行以下操作:

  1. 安装名为svgr的 Webpack 加载器
yarn add --dev @svgr/webpack
Run Code Online (Sandbox Code Playgroud)
  1. 更新您的webpack.config.js
  ...
  module: {
    rules: [
      ...
      // SVG loader
      {
        test: /\.svg$/,
        use: ['@svgr/webpack'],
      }
    ],
  },
  ...
Run Code Online (Sandbox Code Playgroud)
  1. 将 SVG 文件导入为 React 组件
import SomeImage from 'path/to/image.svg'

...

<SomeImage width={100} height={50} fill="pink" stroke="#0066ff" />
Run Code Online (Sandbox Code Playgroud)