React中的SVG操纵

3
我将尝试创建一个简单的SVG图形,显示在线上的设备。这个设备应该有一个标签在下面。我希望标签不重叠:示例图片。由于我正在使用React,所以我想在render()函数中用JSX语法编写SVG代码。因此,为了简单起见,让我们假设我只有:

Equipment class

const Equipment = (props) => (
    <g>
        <rect
          x={props.x}
          y={props.y}
          width={props.width}
          height={props.height}
          fill={black}
        />
        <text
          x={props.x}
          y={props.y}
          fill={black}
          fontSize={props.size}
        >
            {props.text}
        </text>
    </g>
);

export default Equipment;

SVG主要类

import Equipment from './Equipment';

const SVG = (props) => (
    <svg
      width='100%'
      height='100%'
    >
        <g transform={`matrix(${props.matrix})`}>
            <Equipment
              x={10}
              y={10}
              width={100}
              height={100}
              fontSize={props.size}
              test='Equipment 1'
            />
            <Equipment
              x={60}
              y={10}
              width={50}
              height={100}
              fontSize={props.size}
              test='Equipment 2'
            />
        </g>
    </svg>
);

export default SVG;

我使用转换矩阵来缩放SVG中的所有内容,但保持文本大小与矩阵中的比例常数相同。
以下是需要翻译的内容:
  1. 如何确保标签不重叠?
  2. 是否有声明性方式,还是我必须使用while循环?
注意:当手动创建SVG对象并使用SVG函数(例如checkIntersection或getIntersectionList)时,肯定可以轻松地完成此操作,但这些函数在React组件上不可用,我想保留JSX语法。
1个回答

0
考虑添加一个名为textPositionY的属性,表示文本的垂直位置。还可以添加一个函数,根据SVG元素的索引生成该位置。类似于以下内容:
 {
   svgArray.map((eachSVG, index) => {
      const pxFromTop = 20;
      const generateTextPositionY = ix => fixedPosition + ix * pxFromTop;
      const currentTextPositionY = generateTextPositionY(index);
      const svgKey = `svgKey-${index}`

      return (
        <YourSVGComponent
          key={svgKey}
          textPositionY={currentTextPositionY}
          ...your other props
        />
   )})
 }

接下来,使用这个属性,您可以为文本设置样式,因为您知道每个文本距离顶部的像素数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接