边框不是直接应用于 svg 元素而是应用于其子元素?

Border is not applied directy to svg element but to its children elements?

那是我的 stackblitz/codepen: https://stackblitz.com/edit/svgtest?file=index.tsx

当我将鼠标悬停在 svg 矩形上时,悬停事件会触发,因为 facade/roof 的父 svg 元素,所以我希望将边框添加到 svg 元素,但事实并非如此!相反,所有 svg 子元素自己都设置了边框。

这是为什么?

OnMouseOver 已为 svg 元素注册,您可以在此处看到:

   return <svg
      onMouseOver={e => this.props.currentMounting.onMountingHoveredOver(e)}
      onMouseOut={e => this.props.currentMounting.onMountingHoveredOut(e)}
      onClick={e => this.props.currentMounting.onMountingSelected(e.currentTarget.id)}
      opacity={this.props.currentMounting.opacity}
      style={{ fill: 'red' }}
      id={this.props.currentMounting.id}>

      <rect x="0" y="0" height="60" width="60" />
      <rect x="70" y="0" height="60" width="60" />
    </svg>

但是尽管如此,当我将鼠标悬停在它们上面时,所有的矩形元素都会显示边框!?

尝试将悬停事件和其他需求带到 "rect" 级别而不是 svg 标签级别:

示例:

return <svg
  onClick={e => this.props.currentMounting.onMountingSelected(e.currentTarget.id)}
  opacity={this.props.currentMounting.opacity}
  style={{ fill: 'red' }}
  id={this.props.currentMounting.id}>

  <rect onMouseOver={e => this.props.currentMounting.onMountingHoveredOver(e)}
  onMouseOut={e => this.props.currentMounting.onMountingHoveredOut(e)} x="0" y="0" height="60" width="60" />
  <rect onMouseOver={e => this.props.currentMounting.onMountingHoveredOver(e)}
  onMouseOut={e => this.props.currentMounting.onMountingHoveredOut(e)} x="70" y="0" height="60" width="60" />
</svg>

<svg> 个元素是 container elements. That means that they are not painted themselves, but can group child elements that are graphics elements.

如果您在容器元素上设置 stroke 样式 属性,则它没有任何效果。唯一发生的事情是它由子项继承,如果它们是图形元素,将渲染笔划。

如果<svg>是直接嵌入HTML元素的最外层元素,则可以设置border属性。但是就像你的情况一样,它们嵌套在另一个 <svg> 中,唯一的解决方案是绘制一个矩形(在其他矩形之前)覆盖元素的整个视口并在其上设置笔划:

<rect width="100%" height="100%"
     onMouseOver={e => this.props.currentMounting.onMountingHoveredOver(e)}
     onMouseOut={e => this.props.currentMounting.onMountingHoveredOut(e)}
     style={{ fill: 'none' }}>