【问题标题】:React : Returning SVG contents as variable?反应:将 SVG 内容作为变量返回?
【发布时间】:2018-03-31 11:22:07
【问题描述】:

我目前正在这样做:

class Checked extends React.Component {
    render() {
        return (
            <svg width="24" fill="#00ea00" height="24" viewBox="0 0 24 24">
                <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
            </svg>
        );
    }
}

但我想做这样的事情:

import imgTable from '../img/catering_table.svg'

class Checked extends React.Component {
  render() {
      return imgTable;
  }
}

为什么这不起作用?我在这里返回变量而不是实际内容吗?我原以为两者是等价的。

PS:Webpack 设置正确,我在该文件的其他地方使用导入,所以不是这样。 (顺便说一下,我这里用的是 GatsbyJS)

【问题讨论】:

    标签: javascript reactjs svg gatsby


    【解决方案1】:

    选项 1:用无状态组件包装:

    const ImgTable = () => (
      <svg width="24" fill="#00ea00" height="24" viewBox="0 0 24 24">
          <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
      </svg>
    );
    
    export default ImgTable;
    

    现在您可以将其作为组件导入:

    import ImgTable from '../img/ImgTable'
    
    class Checked extends React.Component {
      render() {
          return <ImgTable />;
      }
    }
    

    选项 2:使用 dangerouslySetInnerHTML(注意名称)。但是,您需要在导入时使用 babel-plugin-transform-svg-import-to-string 之类的东西将 SVG 转换为字符串:

    import imgTable from '../img/catering_table.svg' // this will return a string
    
    class Checked extends React.Component {
      render() {
          return <div dangerouslySetInnerHTML={{__html: imgTable }} />;
      }
    }
    

    【讨论】:

    • 最后我意识到这对 OP 没有帮助。他想从 .svg 文件中插入他的 svp。它可以用一个包装器和dangerouslySetInnerHTML={svg_content}
    【解决方案2】:

    babel-plugin-inline-react-svg 是一个插件,可让您完全按照您在问题中暗示的方式进行操作。它只是为 svg 文件中的每个节点创建一个反应组件。然后它用一个你可以轻松命名的根元素包装整个组件树。

    import SampleSVG from './sample.svg'; 这样导入你的 svg。并像这样&lt;SampleSVG /&gt; 在您的应用程序中呈现它。既安全又简单。

    【讨论】:

      【解决方案3】:

      您可以将 SVG 传递给 React 中的变量,如下所示:

        const checkIcon = {
          icon: <svg data-name="Group 1642" width="25.771" height="25.771" className="info--text-icon" viewBox="0 0 25.771 25.771">
            <path data-name="Path 99" d="M11.979 17.51h-.021a.97.97 0 01-.694-.313l-4.889-5.309a.971.971 0 011.429-1.316l4.2 4.566L23.661 3.521a.971.971 0 111.371 1.375L12.665 17.231a.972.972 0 01-.686.279z" fill="#44bbc7" ></path><path data-name="Path 100" d="M12.885 25.771a12.885 12.885 0 010-25.771.971.971 0 010 1.943 10.943 10.943 0 1010.943 10.942.971.971 0 011.943 0 12.9 12.9 0 01-12.886 12.886z" fill="#44bbc7" ></path>
          </svg>
        };
      

      然后调用变量:

      const Informations = () => {
        return (
            <>
             {check.icon} This is SVG with React
            </>
        )
      }
      

      【讨论】:

      • 变量的使用不会是{checkIcon.icon}吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      相关资源
      最近更新 更多