本文介绍了在 React 组件中将 SVG 字符串转换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 React 组件中有一个动态生成的 SVG 字符串.我想将其作为图像嵌入到组件中.目前,我正在使用以下内容:

I have a dynamically generated SVG string in a React component. I want to embed this as an image in the component. Currently, I'm using something along the lines of:

class SomeComponent extends React.Component {
    render() {
        var image = '<svg xmlns="http://www.w3.org/2000/svg" version="1.2" baseProfile="tiny" width="47.4" height="40.65" viewBox="21 18.5 158 135.5"><path d="M25,50 l150,0 0,100 -150,0 z" stroke-width="4" stroke="black" fill="rgb(128,224,255)" fill-opacity="1" ></path><path d="M25,50 L175,150 M25,150 L175,50" stroke-width="4" stroke="black" fill="black" ></path><g transform="translate(0,0)" stroke-width="4" stroke="black" fill="none" ><circle cx="100" cy="30" r="7.5" fill="black" ></circle><circle cx="70" cy="30" r="7.5" fill="black" ></circle><circle cx="130" cy="30" r="7.5" fill="black" ></circle></g></svg>';
        return (
            <div dangerouslySetInnerHTML={{ __html: image }} />
        )
    }
}

然而,使用名为 dangerouslySetInnerHTML 的属性让我很不安.有没有更普遍接受(更安全)的方法来做到这一点?

However using a property called dangerouslySetInnerHTML makes me pretty uneasy. Is there a more generally accepted (and safer) way to do this?

推荐答案

由于 SVG 是动态生成的,您无法将其存储为资产,作​​为 dangerouslySetInnerHTML 的替代方案,您可以简单地将其设置为图像上的 Data URI.所以像...

Since the SVG is dynamically generated and you can't store it as an asset, as an alternative to dangerouslySetInnerHTML, you could simply set it as a Data URI on the image. So something like...

)}}

请参阅此处的帖子:https://css-tricks.com/lodge/svg/09-svg-data-uris/

这篇关于在 React 组件中将 SVG 字符串转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 19:01