首页 > 解决方案 > Lit-Element 绑定到 svg 图像。TypeError:无法读取 null 的属性“拆分”

问题描述

我一直在尝试将一个简单的 url(字符串)绑定到 svg 元素内的图像标签。
但我收到以下错误:TypeError: Cannot read property 'split' of null浏览器中没有显示图片。

图像和绑定工作正常,在普通<img>标签内或在<image/>元素中硬编码时没有错误。

SVG 示例:

import { LitElement, svg } from 'lit-element';

class AppDevice extends LitElement {
static get properties() {
    return {
        selectedImage: {
            type: String
        }
    };
}

constructor() {
    super();
    this.selectedImage = 'https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png';
}

render() {
    return svg`

        <svg width="600px" height="600px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

             <image xlink:href="${this.selectedImage}" id="canvas" x="176.32" y="145.932" width="252.068" height="252.068"/>
             <!-- Works -->
             <!-- <image xlink:href="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" id="canvas" x="176.32" y="145.932" width="252.068" height="252.068"/>      -->

        </svg>

`;
}
}

解决方法示例:

在阅读了这个问题的评论中指出的 github 上的讨论后,我更新了我的答案:

在此处输入图像描述

const namespaced = directive((namespace, value) => (part) => {
       part.committer.element.setAttributeNS(namespace, part.committer.name, value);
    });

const xlinkNamespace = 'https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png';

import { LitElement, html } from 'lit-element';

class AppDevice extends LitElement {
  static get properties() {
    return {
    };
   }

constructor() {
  super();
}

render() {
   return html`

    <svg width="600px" height="600px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

      <image xlink:href="${namespaced(xlinkNamespace, 'something')}" id="canvas" x="176.32" y="145.932" width="252.068" height="252.068"/>

    </svg>

    `;
}
}

标签: javascriptdata-bindingpolymerlit-elementlit-html

解决方案


由于我无法从评论中获得示例,因此我想出了一个不同的解决方案来解决我的问题。尽管这不是我正在寻找的确切答案,但我认为将其发布在这里可能仍然是一个好主意。

不用多说,我的解决方案:
我利用 css 剪辑路径在我的 SVG 元素中显示图像,特别是能够通过绑定来切换它。

这是一篇关于剪辑和遮罩的文章

<img .src="${this.selectedimg}" style="clip-path: url(#myClip);" width="250" height="250">

<svg>
  <defs>
    <clipPath id="myClip">
      <rect width="250" height="250"/>
    </clipPath>
  </defs>
</svg>

推荐阅读