【问题标题】:Why svg embeded in javascript not working为什么嵌入在 javascript 中的 svg 不起作用
【发布时间】:2021-02-10 09:43:22
【问题描述】:

我需要像这样在 Rails html 中使用 react 项目的一些原因:

<html>
  ...
  <script src="<react_project_bundle_file>.js"></script>
</html>

因为这个 React 项目中的图标使用了很多 SVG 图像,所以我尝试使用 svg-sprite-loadersvgo-loader 进行重构。 第一次访问访问该页面时效果很好,但是第二次访问该页面时,这些SvgIcon都没有出现。

// svg-icon.jsx
import '../icons';

const SvgIcon = props => (
    <svg>
        <use xlinkHref={`#icon--${props.icon}`} />
    </svg>
);
// icons/index.js

const requireAll = requireContext => requireContext.keys().forEach(requireContext);
// `icons/svg` is a subdirectory to store all SVG files
const req = require.context('./svg', false, /\.svg$/);
requireAll(req);

和 svg inline 在 bundle js 文件中:

"use strict";
...

var symbol = new _node_modules_svg_baker_runtime_browser_symbol_js__WEBPACK_IMPORTED_MODULE_0___default.a({
  "id": "icon--file-upload",
  "use": "icon--file-upload-usage",
  "viewBox": "0 0 20 20",
  "content": "<symbol xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" id=\"icon--file-upload\"><path d=\"M5.917 6.886L9.64 3.165a.54.54 0 01.777 0l3.721 3.721c.355.355.096.94-.395.94h-1.854L10.784 12.2a.798.798 0 01-.968.573.78.78 0 01-.586-.573L8.126 7.825H6.313c-.491 0-.75-.584-.396-.939zM17 11.602v2.249A3.147 3.147 0 0113.865 17H6.149A3.15 3.15 0 013 13.851v-2.25c0-.572.463-1.022 1.022-1.022.56 0 1.023.45 1.023 1.023v2.249c0 .6.49 1.104 1.104 1.104h7.716c.6 0 1.09-.504 1.09-1.104v-2.25c0-.572.464-1.022 1.023-1.022.572 0 1.022.45 1.022 1.023z\" fill=\"#FFF\" fill-rule=\"evenodd\" /></symbol>"
});

...

HTML 元素调试

  • 第一次访问

    <svg>
      <use xlink:href="#icon--upload">
        #shadow-root(closed)
        <svg xmlns="http://www.w3.org/2000/svg" ...>
          <path ...>
        </svg>
      </use>
    </svg>
    
  • 第二次访问:

    <svg>
      <use xlink:href="#icon--upload">
        #shadow-root(closed)
        !!! not anything !!!
      </use>
    </svg>
    

这里有什么问题?为什么第一次正确,第二次不正确?

【问题讨论】:

标签: javascript html ruby-on-rails reactjs svg


【解决方案1】:

Svg sprite 不包含!

fetch('svg-sprite.svg')
  .then(res => res.text())
  .then(data => {
    document.getElementById('svg-sprite').innerHTML = data;
  });

更新:

svg-sprite.svg 未找到! 已在&lt;svg&gt;&lt;/svg&gt; 中添加路径&lt;use xlinkHref={`static/svg-sprite.svg#icon--${icon}`} /&gt;

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2022-01-19
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
相关资源
最近更新 更多