You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在TSX文件中使用<use>标签的xlink:href属性触发TypeScript错误

这个问题我之前也碰到过!在TSX语法里,像xlink:href这种带冒号的属性名会被JSX解析器当成标识符的分隔符,不符合TSX的语法规范,所以才会抛出“Identifier expected”的错误。这里有两个靠谱的解决办法:

方法一:使用驼峰式属性名(推荐)

JSX/TSX针对XML命名空间的属性有专门的处理方式,只需要把xlink:href改成驼峰式的xlinkHref就可以了,这是官方认可的写法:

import { Component, Prop } from '@stencil/core';
@Component({
  tag: 'example-component',
  styleUrl: 'example-component.scss',
})
export class ExampleComponent {
  render() {
    return (
      <svg>
        <use href="#iconid" xlinkHref="#iconid"/>
      </svg>
    );
  }
}

方法二:仅保留href属性(更简洁)

从SVG2规范开始,主流浏览器已经支持直接使用href属性替代xlink:href,不需要额外的命名空间。如果你的项目不需要兼容非常老旧的浏览器(比如IE11及更早版本),完全可以只保留href属性,这样代码更简洁,也不会有语法问题:

import { Component, Prop } from '@stencil/core';
@Component({
  tag: 'example-component',
  styleUrl: 'example-component.scss',
})
export class ExampleComponent {
  render() {
    return (
      <svg>
        <use href="#iconid"/>
      </svg>
    );
  }
}

这两种方法都能解决你遇到的编译错误,根据你的浏览器兼容性需求选一个就行~

内容的提问来源于stack exchange,提问作者pennyroyal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:31:59