【问题标题】:How to render an SVG on the DOM in react 18?如何在 React 18 中渲染 DOM 上的 SVG?
【发布时间】:2022-11-14 13:44:35
【问题描述】:

我看到很多人一直在讨论一些行不通的东西。

我正在使用 React 18。我想在我的磁盘上导入一个 SVG 文件并在我的 DOM 上渲染它。

我试图将其导入为:

import { ReactComponent as Underconstruction } from '../../media/business/under-construction.svg';

const Sidebar= ()=> {
  return <Underconstruction />
}

但它向我展示了这个错误:

我也尝试将它用作常规图像标签,但它向我显示了同样的错误:

const Sidebar= ()=> {
  return <img src={require('../../media/business/under-construction.svg')} />
}

我尝试使用require(),但它显示 404 找不到文件:

const Sidebar= ()=> {
  return <img src="../../media/business/under-construction.svg" />
}

我正在使用 create-react-app

我正在使用反应 18。

2022 年 10 月 20 日。

【问题讨论】:

  • 试试const Sidebar = () =&gt; Underconstruction

标签: reactjs


【解决方案1】:

将 svg 用作 React 组件的最简单方法。所以你不需要关心配置

import React from 'react'

export function YourFileName() {
  return (
    <svg
     ...
    >
      <path
        ...
        ...
      />
    </svg>
  )
}

您可以通过代码编辑器(如 vscode)打开 svg 来获取 svg 标签

【讨论】:

    【解决方案2】:

    以下是将 SVG 导入 React 的几个选项:

    • 在 react 中将 SVG 作为图像标签导入
    • 在 React 中导入 SVG 作为 JSX
    • 将 SVG 作为反应组件导入(内联 SVG)

    在 React Image 标签中导入 SVG

    import myLogo from '/path/to/image.svg'
     
    const Button = () => {
      return (
        <button>
          <img src={myLogo} alt="SVG logo image"/>
        </button>
      );
    }
    

    在 React 中将 SVG 导入为 JSX

    <svg 
      xmlns="http://www.w3.org/2000/svg"
      class="h-6 w-6"
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
      stroke-width="2"
    >
      <path 
      stroke-linecap="round"
      stroke-linejoin="round"
      d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
      />
    </svg>
    

    将 SVG 导入为 React 组件

    export const LeftArrow = () =>{
      return(
        <svg 
        xmlns="http://www.w3.org/2000/svg"
        className="h-6 w-6"
        fill="none"
        viewBox="0 0 24 24"
        stroke="currentColor"
        strokeWidth={2}
      >
        <path 
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
      />
      </svg>
      )
    }
    

    现在,您可以像这样在另一个组件中导入和渲染 React SVG 组件:

    import { LeftArrow } from './path/to/LeftArrow.jsx'
     
    export const Button = () =>{
      return(
        <button>
          <LeftArrow />
        </button>
      )
    }
    

    【讨论】:

      【解决方案3】:

      最简单的方法是将您的 svg 放入 public 文件夹中,如下所示

      然后你可以直接使用路径使用它,而不用作为组件导入:

      <img src="/media/business/under-construction.svg" />
      

      希望对您有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-27
        • 2023-02-10
        • 1970-01-01
        • 2020-03-23
        • 2021-10-01
        • 2015-11-03
        • 2020-11-04
        • 2021-08-04
        相关资源
        最近更新 更多