【问题标题】:React component inside an SVG element在 SVG 元素中反应组件
【发布时间】:2020-08-18 09:45:04
【问题描述】:

我想在 SVG 中嵌入一个自定义反应组件,但它不起作用。它甚至允许在 SVG 中使用吗?如果没有,是否有解决方法? 下面是我的代码,尝试插入 Modal 组件:

<polygon
        id="Paris"
        <Modal show={show} handleClose={hideModal}>
          <p>Modal</p>
          <p>Data</p>
        </Modal>
        <button type="button" onClick={showModal}>
          open
        </button>
        stroke="#010101"
        fill="rgb(251, 106, 106)"
        stroke-width="2"
        stroke-miterlimit="10"
        points="1596.182,374.685 .../>

我想要完成的是当我们点击 svg 地图中的一个省份时显示一个弹出窗口。

【问题讨论】:

  • 取决于 实际做什么?它是否会导致创建带有 HTML 子级的 节点(好),或者在没有 包装器的情况下插入一些随机 HTML(坏)? SVG 中的 HTML 内容必须包装在 节点中,

标签: reactjs svg components


【解决方案1】:

对于您想要实现的目标,我会将 svg 包装在模态框内。像这样的:

<Modal>
   <svg></svg>
</Modal>

在您的模态组件中,确保将 svg 显示为子项:

return (
    <Fragment>
      {props.children}
    </Fragment>
  );

查看文档了解更多信息:https://reactjs.org/docs/composition-vs-inheritance.html

【讨论】:

    【解决方案2】:

    根据@Robert Longson 的评论,我将 Modal 组件插入到 foreignObject 中,它可以工作。就 x, y 坐标而言,模态窗口仍然需要手动调整,以便它完全弹出单击的 svg 元素:

     <foreignObject x="58%" y="6%" width="200px" height="250px">
            <Modal show={show} handleClose={hideModal}>
              <p style={{ padding: "10px" }}>Modal</p>
              <p>Data</p>
            </Modal>
    </foreignObject>
    

    请注意,您必须设置 x、y、height、width 属性才能使其正常工作,如本答案 React - html tags inside svg 中所述

    【讨论】:

      猜你喜欢
      • 2017-02-04
      • 2020-11-10
      • 2020-05-21
      • 2021-05-14
      • 2017-12-25
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      相关资源
      最近更新 更多