我正在研究一个需要接受SVG作为道具的React组件。
如果没有提供道具,我有一个默认的svg,但如果提供了,那么默认的svg可以用prop接受的版本替换。
所以组件就像。
<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件事?
更新:我在下面的答案中尝试了其中一种方法,但它似乎不起作用。这是我所拥有的CodeSandbox的链接 - codesandbox.io/s/n0yzv9yyvp
答案 0 :(得分:0)
我在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标记的常用参数,您可以根据需要省略或重写它们
答案 1 :(得分:0)
您最好的选择是使用数据URI。
示例:
<img src='data:image/svg+xml;utf8,<svg ... > ... </svg>'>
在这里阅读更多内容: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
答案 2 :(得分:0)
您可以像其他任何组件一样将道具传递给svg组件
例如
function App() {
return <Svg height={20} width={20} fill={black} />;
}
const Svg = ({ height, width, color }) => (
<svg
height={height}
width={width}
fill={color}
xmlns="http://www.w3.org/2000/svg"
></svg>
);