【问题标题】:Add attributes to a path svg component for a map in React在 React 中为地图的路径 svg 组件添加属性
【发布时间】:2021-11-24 00:43:13
【问题描述】:

我正在尝试实现一个使用我创建的 svg 地图的策略游戏,并且我想在每个“路径”(这将是领土)和其他一些道具中添加一些属性,例如“部队”。是否可以仅将 att(props) 添加到路径,然后在作为整个地图的 svg 标记内使用此组件。所以基本上我想知道如何在地图中创建一个带有 att(props) 和输入或标签的区域对象,以便稍后我可以添加 onClick 事件和其他事件。

现在我有组件 Map 和 Territory 组件(我不确定这是否是处理它的最佳方式。)

const Territory = ({ tD }) => {
  const [color, setColor] = useState('red')
  const [troops, setTroops] = useState(21)

  return (
    <>
      <input type="text" />
      <path fill-rule="evenodd" clip-rule="evenodd" d={tD} fill={color} stroke="black" />
    </>
  );
};

export default Territory;

const Map = () => {
  return (
    <svg width="1397" height="686" viewBox="0 0 1397 686" fill="none" xmlns="http://www.w3.org/2000/svg">
      {territories.map(territory => (
        <Territory key={territory.id} tD={territory.tD} />
      ))}
    </svg>

  );
};

我想在每个领土的地图的输入或标签中添加部队可见(数字)。像这样的东西 map with inputs

有可能吗?构建具有“部队”等道具的领土组件的最佳方法是什么

非常感谢帮助我的人。

【问题讨论】:

    标签: javascript reactjs svg next.js


    【解决方案1】:

    您将正常的HTML &lt;input /&gt; 渲染为svg 的一部分,这不起作用。如果有任何东西不是svg 的一部分,并且您将其渲染为svg 的子级,那么您必须将其包装为foreignObject

    区域组件

    const Territory = ({ tD }) => {
      const [color, setColor] = useState('red')
      const [troops, setTroops] = useState(21)
    
      return (
        <g>
          <foreignObject x="40" y="40" width="100" height="100">
            <div xmlns="http://www.w3.org/1999/xhtml">
              <input type="text" />
            </div>
          </foreignObject>
          <path fill-rule="evenodd" clip-rule="evenodd" d={tD} fill={color} stroke="black" />
        </g>
      );
    };

    注意:

    • 不要忘记heightwidth 属性。您可能还需要xy
    • 不要忘记容器 HTML 元素上的xmlns="http://www.w3.org/1999/xhtml"
    • 您可以使用svg &lt;g /&gt;标签对元素进行分组。

    【讨论】:

    • 感谢您的帮助!我现在有时间去看它并开始工作。有效 :) 。我唯一需要做的就是找到正确位置的 X 和 Y。
    猜你喜欢
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 2017-02-07
    • 1970-01-01
    • 2015-11-05
    • 2016-08-01
    相关资源
    最近更新 更多