reactjs - 接受 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 我要找的东西?
- 从路径加载 svg 并应用道具(颜色、高度、宽度)?
- 如果 src 道具本身有 SVG,我们如何显示它并应用道具(颜色、高度、宽度)
更新:我在下面的答案中尝试了一种方法,但它似乎不起作用。这是我现有的 CodeSandbox 的链接-codesandbox.io/s/n0yzv9yyvp
解决方案
我经常在 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
,width
和height
是image
svg 标签的常用参数,您可以根据需要省略或重写它们
推荐阅读
- android - 无法使用 ML Kit Firebase 从文本识别中获取文本
- c - 我必须创建两个调度程序线程,我的代码中出现分段错误,但我不明白为什么会这样。有人能帮忙吗?
- javascript - 即使我使用 catch 向用户呈现消息,页面也会出错
- tkinter - Tkinter 文本不适合页面
- sql - SQL - 使用带有可变表值的 SET
- angular - Angular 6.x 独立组件样式包
- javascript - 删除 jQuery UI 中动态创建的选项卡
- python-3.x - 使用 langdetect 输出导入到我的数据框中的新列
- python - 在 Python 中替换 docx 字符串中的数字
- python - 无论如何可以从 Python 上的 Yahoo Finance DatasReader 计算 Market Beta 吗?