SVG <path>元素内文本不显示?React组件技术求助
解决SVG 内无法显示文本的问题
SVG的<path>是图形元素,不能直接嵌套HTML的<p>、<h1>等文本元素,这是SVG的DOM结构规则决定的。你有两种可行方案:
方案1:用SVG原生<textPath>让文本沿路径排列
适合需要文本贴合路径轮廓的场景,无需引入HTML元素:
export default function Segment({ pathData, keyName }) { const pathId = `segment-path-${keyName}`; return ( <svg> {/* 给path添加唯一id,供textPath引用 */} <path id={pathId} d={pathData} stroke='red' fillOpacity={0.1} fill="green" /> <text fill="black" fontSize="16"> <textPath href={`#${pathId}`} startOffset="50%" textAnchor="middle" > I want to put some text here, like the {keyName} </textPath> </text> </svg> ); }
startOffset="50%"和textAnchor="middle"用于将文本居中对齐到路径- 必须将
<path>和<text>放在同一个<svg>容器内
方案2:用<foreignObject>嵌入HTML内容
适合需要复杂HTML样式(比如背景色、多行文本、排版)的场景:
import { useRef, useEffect, useState } from 'react'; export default function Segment({ pathData, keyName }) { const pathRef = useRef(null); const [box, setBox] = useState({ x: 0, y: 0, width: 0, height: 0 }); // 组件挂载后获取path的包围盒尺寸 useEffect(() => { if (pathRef.current) { const bbox = pathRef.current.getBBox(); setBox({ x: bbox.x, y: bbox.y, width: bbox.width, height: bbox.height }); } }, [pathData]); return ( <svg> <path ref={pathRef} d={pathData} stroke='red' fillOpacity={0.1} fill="green" /> {/* 用foreignObject包裹HTML元素,必须指定xmlns */} <foreignObject x={box.x} y={box.y} width={box.width} height={box.height} > <div xmlns="http://www.w3.org/1999/xhtml" style={{ backgroundColor: 'purple', color: 'white', width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }} > I want to put some text here, like the {keyName} </div> </foreignObject> </svg> ); }
- 通过
getBBox()动态获取path的位置和尺寸,确保HTML内容覆盖path区域 - 包裹HTML的元素必须声明
xmlns="http://www.w3.org/1999/xhtml",否则浏览器无法识别HTML样式
内容的提问来源于stack exchange,提问作者Mo0rBy
相关产品推荐
相关产品推荐

