【发布时间】: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 我已经更新了第一个代码块
-
您可以在这两种情况下使用
<SvgIcon viewBox={viewBox} />,viewBox未定义不会破坏逻辑。 -
ref.current.children[0] .. 这真的是 SVGElement 吗?尝试将 ref.current.children[0] 附加为 SVGElement
-
这确实是@JGFMK 的解决方案。谢谢
标签: reactjs typescript svg