如何在<text>中隐藏/显示<g>元素?

问题描述 投票:0回答:1
用反应,我正在显示以下

<g> <rect x={x} y={y} width={width} height={height} /> <text x={x + width / 2} y={y + height / 2 + 7} textAnchor="middle"> {someText} </text> </g>
但考虑到

width

的值,我想显示或隐藏我的
<text>
元素。
or,我希望我的文本元素与overflow: ellipsis
文本元素相比w
width
ie,如果是

width = 100

width of my <text> element = 200
,则显示50%的
<text>
,并将
...
附加到
someText
浏览Mozilla文档和一些SVG文档,我发现很明显。
这样做是什么最聪明,最有效的方式?

SVG没有对溢出的内置支持:省略号,但是您可以通过测量文本宽度并在必要时截断它来实现相同的效果。

import React, { useState, useEffect, useRef } from "react"; const TruncatedText = ({ x, y, width, height, someText }) => { const textRef = useRef(null); const [displayText, setDisplayText] = useState(someText); useEffect(() => { if (textRef.current) { const textWidth = textRef.current.getBBox().width; if (textWidth > width) { let truncated = someText; while (textRef.current.getBBox().width > width && truncated.length > 0) { truncated = truncated.slice(0, -1); // Remove last character setDisplayText(truncated + "..."); } } } }, [someText, width]); return ( <g> <rect x={x} y={y} width={width} height={height} fill="lightgray" /> {displayText && ( <text ref={textRef} x={x + width / 2} y={y + height / 2 + 7} textAnchor="middle"> {displayText} </text> )} </g> ); }; export default TruncatedText;

javascript css reactjs svg
1个回答
0
投票

{displayText.length > 3 && ( <text ref={textRef} x={x + width / 2} y={y + height / 2 + 7} textAnchor="middle"> {displayText} </text> )}

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.