【问题标题】:How do I use SVGs for background images on buttons in React如何在 React 中的按钮上使用 SVG 作为背景图像
【发布时间】:2021-01-12 16:51:57
【问题描述】:

堆栈溢出的第一个计时器,所以我会尽力而为。

我正在尝试动态添加 SVG 作为按钮的背景图像。

使用 create-react-app 创建了 react 应用。 我有 3~ 个有问题的文件:poland.svg、Flag.jsx 和 exampleComponent.jsx


exampleComponent.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

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;

波兰.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>

我正在获取文件路径 /static/media/poland.49b43928.svg 当我检查 chrome 中的元素时,会显示正确的文件路径,但未加载 SVG!

我还是个菜鸟!所以请严厉! ;D

【问题讨论】:

  • poland.svg 无效,因为它缺少 SVG 命名空间。

标签: javascript reactjs svg create-react-app


【解决方案1】:

更新!所以文件是以 XML 格式发送的。我希望我知道更多来解释细节,但我为解决这个问题所做的只是添加: xmlns="http://www.w3.org/2000/svg"

像这样的 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>

【讨论】:

    【解决方案2】:

    如果svg文件相似,可能匹配有问题

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

    其中 xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxxxx 是 ID,每个文件必须是唯一的。

    查看链接,可能会有帮助

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

    【讨论】:

    • 感谢您的快速响应! :D 我会试一试的!
    猜你喜欢
    • 2020-06-02
    • 2019-12-16
    • 2012-07-16
    • 2017-01-10
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    相关资源
    最近更新 更多