【问题标题】:Type 'Element' is missing the following properties from type 'SVGSVGElement'“元素”类型缺少“SVGSVGElement”类型的以下属性
【发布时间】:2020-12-20 07:02:18
【问题描述】:

所以我有以下情况,TypeScript 让我发疯。

案例:我收到一个带有 SVG 作为子元素的 div。我需要从该子 SVG 元素接收 x、y、宽度和高度属性。

 ...
 const ref = React.useRef<HTMLDivElement>(null)
  React.useEffect(() => {
    if (!viewBox) {
      if (ref.current !== null) {
        const svg: SVGElement = ref.current.children[0]

        // Get the basic x, y, width, height values from the svg element
        const x = svg.x.baseVal.value,
          y = svg.y.baseVal.value,
          width = svg.width.baseVal.value,
          height = svg.height.baseVal.value

        // Check if the svg already has a viewbox attribute
        let originalViewBox
        if (svg.attributes.length > 0) {
          Object.values(svg.attributes).forEach((value) => {
            if (value && value.name === 'viewBox') originalViewBox = value.value
          })
        }

        /*
          If there is a viewbox attribute, use those value's.
          Otherwise, we use the svg x, y, width and height attributes
        */
        setViewBox([originalViewBox ? originalViewBox : `${x}, ${y}, ${width}, ${height}`])
      }
    }
  }, [ref, viewBox])

  return (
    // Styled div element that wraps around the svg
    <Icon
      className={`${animated ? 'animated' : ''} ${className}`}
      color={color}
      inline={inline}
      onClick={onClick}
      ref={ref}
      stacked={stacked}
    >
      {/* The svg element. Ref does not work here because it returns current: null */}
      {SvgIcon && !viewBox ? <SvgIcon /> : <SvgIcon viewBox={viewBox} />}
    </Icon>
  )
}
...

但是,即使我将我的 svg 定义为 SVGElement,我仍然从“const svg”收到以下错误

“元素”类型缺少“SVGElement”类型的以下属性:ownerSVGElement、viewportElement、oncopy、oncut 等等。

这个错误来自所有 svg.x、svg.y。 svg.width 和 svg.height 部分:

“SVGElement”类型上不存在属性“width”(或 x、y、height、..)。

当我将第一行更改为:

const svg: SVGSVGElement = ref.current.children[0]

所以,从 SVGElement 到 SVGSVGElement,唯一剩下的错误是 'const svg' 上的错误,它现在显示:

“元素”类型缺少“SVGSVGElement”类型的以下属性:contentScriptType、contentStyleType、currentScale、currentTranslate 和 139 more.ts(2740)

我想知道的是,我需要如何定义我的 svg 元素以避免错误(下面的图片以获得更多许可)

【问题讨论】:

  • 您能否分享一下您定义ref 对象的位置?问题可能来自那里:)
  • @tmhao2005 我已经更新了第一个代码块
  • 您可以在这两种情况下使用&lt;SvgIcon viewBox={viewBox} /&gt;viewBox 未定义不会破坏逻辑。
  • ref.current.children[0] .. 这真的是 SVGElement 吗?尝试将 ref.current.children[0] 附加为 SVGElement
  • 这确实是@JGFMK 的解决方案。谢谢

标签: reactjs typescript svg


【解决方案1】:

由于.children 方法返回一个HTMLCollection,其中每个元素都是Element 对象,您不能将其分配给不同的类型,例如SVGSVGElement。但是您可以强制转换类型以使其适用于您的情况:

const svg = ref.current?.children[0] as SVGSVGElement;

【讨论】:

  • 完美!我试图在开始时声明类型,但诀窍是像你一样在最后做。
猜你喜欢
  • 2020-02-07
  • 2021-04-20
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
  • 2020-10-28
  • 1970-01-01
相关资源
最近更新 更多