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