如何使用 SVG React 组件作为背景?

Kee*_*ing 2 reactjs

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

import React from "react";

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

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

我需要将其渲染为背景:

<div style={{ backgroundImage: `url(${MySVGBackground})` }}> </div>
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

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

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

Jos*_*ers 8

试试这个: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>
  );
}
Run Code Online (Sandbox Code Playgroud)

data: image/svg+xml;utf8部分告诉浏览器原始图像数据在后面。

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