首页 > 解决方案 > 接受 SVG 作为 React 组件的道具

问题描述

我正在开发一个需要接受 SVG 作为道具的 React 组件。

如果没有提供道具,我有一个默认的svg,但是如果提供了它,那么可以用从道具接受的那个替换默认的svg。

所以组件就像。

<MySvg src={path to svg or the svg itself} height={20} width={20} fillColor={'red'} />

组件应该做的就是使用提供的道具显示这个 SVG。我希望 DOM 是这样的。

<svg fill={this.props.fillColor} height={this.props.height} width={this.props.width}>
    <g>
        <rect />
    </g>
</svg>

由于每个 SVG 都是不同的,这意味着它可能有一个多边形、矩形、g 等,那么实现这一点的最佳方法是什么?

2 我要找的东西?

  1. 从路径加载 svg 并应用道具(颜色、高度、宽度)?
  2. 如果 src 道具本身有 SVG,我们如何显示它并应用道具(颜色、高度、宽度)

更新:我在下面的答案中尝试了一种方法,但它似乎不起作用。这是我现有的 CodeSandbox 的链接-codesandbox.io/s/n0yzv9yyvp

标签: reactjssvg

解决方案


我经常在 react.js 中使用 SVG,我发现最好的解决方案是使用 embed svg:

<MySvg src={'/path/to/svg'} height={20} width={20} fillColor={'red'} />

在你的组件内部

<svg fill={this.props.fillColor} height={this.props.height} width={this.props.width}>
  <g>
    <image
      x="10"
      y="197"
      width="159"
      height="113"
      xlinkHref={this.props.src}
    />
  </g>
</svg>

x, y,widthheightimagesvg 标签的常用参数,您可以根据需要省略或重写它们


推荐阅读