简体   繁体   English

如何在 React 中的按钮上使用 SVG 作为背景图像

[英]How do I use SVGs for background images on buttons in React

First timer on stack overflow so I'll try my best.堆栈溢出的第一个计时器,所以我会尽力而为。

I'm trying to dynamically add SVGs as background images for my buttons.我正在尝试为我的按钮动态添加 SVG 作为背景图像。

Created react app using create-react-app.使用 create-react-app 创建反应应用程序。 I have 3~ files in question: poland.svg, Flag.jsx and exampleComponent.jsx我有 3~ 个文件有问题:poland.svg、Flag.jsx 和 exampleComponent.jsx


exampleComponent.jsx示例组件.jsx

import React from 'react';
import Flag from './Flag.jsx';

const exampleComponent = (props) => {
  const backgroundImage = {
    backgroundImage: `url(${Flag(props.nation)})`
  }

  return(
    <button style={backgroundImage}>
      <div />
    </button>
  )
}

export default exampleComponent;

Flag.jsx标志.jsx

import Poland from './poland.svg';
import US from './us.svg';

const Flag = (nation) => {
  let path = "";

  if (nation === "Poland") path = Poland;
  else if (nation === "US") path = US;

  return path;
}

export default Flag;

poland.svg波兰.svg

<svg
    height="100%"
    width="100%"
>
    <defs />
    <rect fill="#ffffff" width="100%" height="50%" />
    <rect transform="translate(0, 50px)" fill="#ff0000" width="100%" height="50%" />
</svg>

I'm getting the file path /static/media/poland.49b43928.svg When I inspect the element in chrome the correct file path is shown but the SVG isn't being loaded!我正在获取文件路径 /static/media/poland.49b43928.svg 当我检查 chrome 中的元素时,会显示正确的文件路径,但未加载 SVG!

IM STILL A NOOB!我还是菜鸟! so please be harsh!所以请严厉点! ;D ;D

Update!更新! So the file was being sent in XML format.. I wish I knew more to explain the details but all I did to fix this was add: xmlns="http://www.w3.org/2000/svg"所以文件以 XML 格式发送.. 我希望我知道更多来解释细节,但我所做的只是添加: xmlns="http://www.w3.org/2000/svg"

to the svg tags like so:到 svg 标签,如下所示:

<svg
    height="100%"
    width="100%"
    xmlns="http://www.w3.org/2000/svg"
>
    <defs />
    <rect fill="#ffffff" width="100%" height="50%" />
    <rect transform="translate(0, 50px)" fill="#ff0000" width="100%" height="50%" />
</svg>

If the svg files are similar, there may be a problem with matching the如果svg文件相似,可能是匹配有问题

<use xlink ID:href="#xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx"/>, 

where xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxxxx is the ID, it must be unique for each file.其中xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxxxx为ID,每个文件必须唯一。

See the link, it may help查看链接,它可能会有所帮助

https://github.com/SilverFox70/svg-react-loader https://github.com/SilverFox70/svg-react-loader

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

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