svg和react_创建React应用程序和svg

本文介绍了如何结合SVG图形与React技术来创建React应用程序。通过引用外部链接的资源,详细阐述了SVG在React中的应用实践。
摘要由CSDN通过智能技术生成

svg和react

SVG stands for Scalable Vector Graphics. It defines vector-based graphics in XML format. Compared to a raster-based bitmap (above left), the vector-based image (above right) preserves the shape while scaling up. In addition, as the nature of XML files, they can be searched, indexed, scripted, compressed, and built with accessibility. SVG is a widely used graphic format on the web.

SVG代表可缩放矢量图形。 它以XML格式定义了基于矢量的图形。 与基于栅格的位图(左上)相比,基于矢量的图像(右上)在放大时保留了形状。 另外,作为XML文件的本质,可以使用可访问性搜索,索引,编写脚本,压缩和构建它们。 SVG是网络上广泛使用的图形格式。

Create React App中的SVG徽标 (SVG Logo in Create React App)

Create React App comes with an SVG logo:

Create React App带有SVG徽标:

Image for post
Image provided by the author.
图片由作者提供。

This logo is defined in src/log.svg:

该徽标在src/log.svg定义:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">      
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>

At the root level, the svg tag defines an SVG document fragment, which has the name space http://www.w3.org/2000/svg and the rectangle viewBox starting from (0,0) point with width 841.9 and height 595.3.

在根级别中, svg标签定义的SVG文档片段,其名称空间http://www.w3.org/2000/svg和矩形viewBox从开始(0,0)点与宽度841.9和高度595.3

The g tag groups elements together. It defines the fill color of the group. The first group are three overlapping ellipses, defined by the path tag. The d attribute is a set of commands which define the path. The commands have two formats:

g标签将元素分组在一起。 它定义了组的fill颜色。 第一组是三个重叠的椭圆,由path标签定义。 d属性是定义路径的一组命令。 命令有两种格式:

  • The upper case commands are actions that use the absolute values.

    大写命令是使用绝对值的操作。
  • The lower case commands are actions that use the relative values.

    小写的命令是使用相对值的动作。
M/m = moveto
L/l = lineto
H/h = horizontal lineto
V/v = vertical lineto
C/c = curveto
S/s = smooth curveto
Q/q = quadratic Bézier curve
T/t = smooth quadratic Bézier curveto
A/a = elliptical Arc
Z/z = closepath

The second group defines the circle tag, which is centered at (420.9, 296.5) with the radius 45.7. The third group defines another path tag that does nothing.

第二组定义circle标签,其中心为(420.9, 296.5) ,半径为45.7 。 第三组定义另一个不执行任何操作的path标签。

It takes 2,671 bytes to define this logo. As pointed out in this issue, the logo SVG can be simplified to 428 bytes with the following definition:

定义此徽标需要2,671个字节。 正如本期所指出的那样,徽标SVG可以简化为428字节,其定义如下:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="none" stroke="#61DAFB" stroke-width="23" >
<ellipse cx="420.9" cy="296.5" rx="235" ry="91" />
<ellipse cx="420.9" cy="296.5" rx="235" ry="91" transform="rotate(120 420.9 296.5)"/>
<ellipse cx="420.9" cy="296.5" rx="235" ry="91" transform="rotate(240 420.9 296.5)"/>
</g>
<circle cx="420.9" cy="296.5" r="45.7" fill="#61DAFB"/>
</svg>

It is a group of three ellipses without filling. The three ellipses have the same center, x-axis radius, and y-axis radius. The second ellipse rotates 120-degree with the center (420.9, 296.5). The third ellipse rotates 240-degree with the center, (420.9, 296.5). The circle is defined outside the group, with the fill color and the default stroke-width set to 1.

它是一组三个没有填充的椭圆。 三个椭圆具有相同的中心,x轴半径和y轴半径。 第二个椭圆以中心(420.9, 296.5)旋转120度。 第三椭圆以中心(420.9, 296.5)旋转240度。 该圆在组外定义, fill颜色和默认stroke-width设置为1

如何在React中使用SVG? (How to Use SVG in React?)

Create React App brings convenience for SVG. You do not need to think about how to configure webpack settings. It has been set up already. There are a number of ways to use SVG in Create React App. We are going to describe them one by one.

Create React App为SVG带来了便利。 您无需考虑如何配置Webpack设置。 已经设置好了。 在Create React App中有多种使用SVG的方法。 我们将一一描述它们。

在JSX中使用SVG (Use SVG in JSX)

SVG can be used in JSX directly.

SVG可以直接在JSX中使用。

import React from 'react';


function App() {
  return (
    <svg>
      <text x="10" y="20">Today is Sunday</text>
    </svg>
  );
}


export default App;

Lines 5-7 define an SVG, which prints out a text: Today is Sunday. Mixing SVG code inside JSX violates separation of concerns, a design principle for separating a computer program into distinct sections for separate concerns. It works, but it is not a recommended method.

第5-7行定义了一个SVG,该SVG会打印出一个文本: Today is Sunday 。 在JSX中混合SVG代码违反了关注点分离,这是一种将计算机程序分为不同部分以实现关注点的设计原则。 它可以工作,但是不建议这样做。

使用SVG作为图像 (Use SVG as an Image)

Using the img tag is how Create React App embeds the logo SVG, which is defined in a separate file, src/logo.svg.

使用img标签是Create React App嵌入徽标SVG的方式,该徽标在单独的文件src/logo.svg

This method is enabled by the built-in file-loader, which is configured by webpack.config.js:

该方法由内置file-loader启用,该file-loaderwebpack.config.js配置:

// "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: {
    ame: 'static/media/[name].[hash:8].[ext]',
  },
},

Put our text SVG into src/logo.svg:

将我们的文本SVG放入src/logo.svg

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 100">
<text x="10" y="20">Today is Sunday</text>
</svg>

Then it can be invoked as an image in JSX:

然后可以将其作为图像在JSX中调用:

import React from 'react';
import logo from './logo.svg';


function App() {
  return (
    <img src={logo} alt="logo" />
  );
}


export default App;

In line 2, the import statement tells webpack to use this image.

在第2行中,import语句告诉webpack使用此映像。

At line 7, the SVG file is used as a normal image via the img tag, where src specifies a url as the path to the image. The configured file-loader resolves import of ./logo.svg into a URL and emits the file into the output directory. The final filename will be generated by webpack from its content hash. In this way, a browser will not use a cached image if image content changes.

在第7行,SVG文件通过img标签用作普通图片,其中src指定一个url作为图片的路径。 配置的file-loader./logo.svg import ./logo.svg为URL,并将文件发送到输出目录。 最终文件名将由webpack从其内容哈希值生成。 这样,如果图像内容发生更改,浏览器将不会使用缓存的图像。

logo.svg can also be placed in the public folder. Then it does not need to be imported. It can be directly used by line 5 in the following way:

logo.svg也可以放在public文件夹中。 然后,无需导入。 第5行可以通过以下方式直接使用它:

import React from 'react';


function App() {
  return (
    <img src={process.env.PUBLIC_URL + 'logo1.svg'} alt="logo" />
  );
}


export default App;

Both ways work, but importing images is the recommended method. In rare cases, images are put into the public folder:

两种方法都可以,但是建议导入图像。 在极少数情况下 ,图像会放在public文件夹中:

  • Specific file names are needed in the build output.

    在构建输出中需要特定的文件名。
  • There are thousands of images, and they need to be dynamically referenced by the paths.

    有成千上万个图像,它们需要由路径动态引用。

使用SVG作为React组件 (Use SVG as a React Component)

This way is enabled by the built-in svgr, which transforms SVG into ready to use components.

内置的svgr启用了这种方法,它将SVG转换为可立即使用的组件。

Let’s run SVGR CLI command for src/logo.svg:

让我们为src/logo.svg运行SVGR CLI命令:

$ npx @svgr/cli --icon --replace-attr-values "#063855=currentColor" src/logo.svg
npx: installed 161 in 26.523s
import * as React from "react";function SvgLogo(props) {
return (
<svg viewBox="0 0 300 100" width="1em" height="1em" {...props}>
<text x={10} y={20}>
{"Today is Sunday"}
</text>
</svg>
);
}export default SvgLogo;

It generates a React component, named SvgLogo. The webpack plugin does this transformation for us.

它生成一个名为SvgLogo的React组件。 webpack插件为我们完成了此转换。

plugins: [
  [
    require.resolve('babel-plugin-named-asset-import'),
    {
      loaderMap: {
        svg: {
          ReactComponent:
            '@svgr/webpack?-svgo,+titleProp,+ref![path]',
          },
        },
      },
  ],
  ...
]...

This transformation names the generate component ReactComponent, which will be unique for each import.

此转换将命名生成组件ReactComponent命名为每个导入都是唯一的。

import React from 'react';
import {ReactComponent as Logo} from './logo.svg';


function App() {
  return (
    <Logo />
  );
}


export default App;

In line 2, ReactComponent is renamed as Logo, which is used as a React component in line 6.

在第2行中, ReactComponent重命名为Logo ,在第6行中用作React组件。

Using SVG as a React Component has significant advantages. ReactComponent accepts props that allow us to configure the SVG component. It also allows a title for accessibility.

使用SVG作为React组件具有明显的优势。 ReactComponent接受支持我们配置SVG组件的道具。 它还允许标题的可访问性。

import React from 'react';
import {ReactComponent as Logo} from './logo.svg';


function App() {
  return (
    <div>
      <Logo title="Orange Text" fill="orange" transform="rotate(-10) translate(10, 200)" />
      <Logo title="Purple Text" fill="purple" transform="rotate(-10) translate(45, 0)" />
      <Logo title="Blue Text" fill="blue" transform="rotate(-10) translate(80, -200)" />
    </div>
  );
}


export default App;

In the above code, Logo has been added three times. Each time (line 7, 8, and 9), the component has its own title, color, and transformation.

在上面的代码中, Logo已添加了3次。 每次(第7、8和9行),组件都有自己的标题,颜色和转换。

Instead of the boring text Today is Sunday, we see the following colorful transformed texts:

Today is Sunday ,而不是无聊的文本,我们看到了以下丰富多彩的转换​​文本:

Image for post

Isn’t that cool?

那不是很酷吗?

使用SVG作为背景图像 (Use SVG as a Background Image)

For the previous example of colorful transformed texts, we can also add an SVG file as background.

对于前面的彩色转换文本示例,我们还可以添加SVG文件作为背景。

We define src/index.css to include the following selector:

我们定义src/index.css包括以下选择器:

div {
background: url(background.svg)
}

The background gradient color is defined in src/background.svg:

背景渐变颜色在src/background.svg定义:

<svg xmlns="http://www.w3.org/2000/svg">
<title>Background gradient</title>
<defs>
<linearGradient id="g" x1="0%" x2="100%" y1="0%" y2="100%">
<stop style="stop-color: green;" offset="0"/>
<stop style="stop-color: yellow;" offset="1"/
</linearGradient>
</defs>
<rect style="fill: url(#g);" width="100%" height="100%"/>
</svg>

It is a good practice to have a title for SVG. This linear gradient color is composed of green and yellow.

SVG的标题是一个好习惯。 这种线性渐变颜色由greenyellow组成。

Our colorful transformed texts become more colorful.

我们丰富多彩的转换​​文本变得更加丰富多彩。

Image for post

结论 (Conclusion)

SVG is powerful for building fast, performant, and accessible webpages. You may wonder how to create a complicated SVG. There are a number of editors to help us. VSCode provides quite a few extensions too. Vectr is a free online editor.

SVG具有强大的功能,可用于构建快速,高性能和可访问的网页。 您可能想知道如何创建复杂的SVG。 有许多编辑器可以帮助我们。 VSCode也提供了很多扩展。 Vectr是免费的在线编辑器。

This is a drawing that we made for fun. It looks pretty to be put it into src/logo.svg with the gradient background.

这是我们取笑的图纸。 看起来很漂亮,可以将它放入带有渐变背景的src/logo.svg

Image for post

The generated SVG file is a bit long. If you are interested, open the following image to check out the 256 lines of code in the Github gist.

生成的SVG文件有点长。 如果您有兴趣,请打开以下图片以查看Github要点中的256行代码。

Happy SVGing! Thanks for reading. I hope this was helpful.

开心的SVGing! 谢谢阅读。 我希望这可以帮到你。

You can see my other Medium publications here.

您可以在这里查看我的其他Medium出版物。

翻译自: https://medium.com/better-programming/create-react-app-and-svgs-70970ac715f2

svg和react

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值