【问题标题】:How to use a SVG React component as background?如何使用 SVG React 组件作为背景?
【发布时间】:2020-04-21 02:04:40
【问题描述】:

我有用函数组件编写的 SVG 文件。

import React from "react";

const MySVGBackground= (props) => {
  return (
    <svg> some svg here</svg>
  );
};

export default MySVGBackground;

我需要将此渲染为背景:

<div style={{ backgroundImage: `url(${MySVGBackground})` }}> </div>

但它不起作用。

我不能直接直接导入 SVG,因为它会给我一个 Unexpected Token 的错误。所以我必须将 SVG 包装到 FC 中并导出。

下面是示例代码: https://codesandbox.io/s/react-background-issue-9wt4x?file=/src/App.js

【问题讨论】:

  • 您的 svg 需要动态吗?如果是这样,您是否打算将道具传递给它?
  • 静态,不传递任何道具。

标签: reactjs


【解决方案1】:

试试这个: https://codesandbox.io/s/react-background-issue-ut933

import React from "react";
import "./styles.css";
import BackgroundSVG from "./backgroundSVG";
// import this to render static markup
import { renderToStaticMarkup } from 'react-dom/server';

export default function App() {
  // convert component to string useable in data-uri
  const svgString = encodeURIComponent(renderToStaticMarkup(<BackgroundSVG />));

  return (
    <div className="App">
      <h2
        style={{
          backgroundImage: `url("data:image/svg+xml,${svgString}")`
        }}
      >
        Svg background
      </h2>
    </div>
  );
}

数据:image/svg+xml;utf8部分告诉浏览器原始图像数据正在跟随。

更多信息可以在这里找到: https://css-tricks.com/lodge/svg/09-svg-data-uris/ https://gist.github.com/iansinnott/2e8fe9d9e4c6c7c55793d38f81c999a3

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-07-16
  • 2020-06-02
  • 2021-01-12
  • 2012-02-29
  • 2021-11-29
  • 2019-12-16
  • 2022-01-12
  • 2020-02-13
相关资源
最近更新 更多