简体   繁体   中英

How do I render and edit SVG data in React?

Let's say that I have an SVG file in my database:

<svg width="400" height="100"> 
  <rect width="400" height="100" 
  style="fill:rgb(0,0,255);stroke-width:10;stroke:rgb(0,0,0)" /> 
</svg> 

It looks like this在此处输入图像描述

And in my React code I fetch the SVG file like so:

fetch('/api/picture')
  .then(res => res.json())
  .then(res => {
    this.setState({
      picture: res
    })
  })

So now in my state, I have a variable called picture whose value is this:

<svg width="400" height="100"> 
  <rect width="400" height="100" 
  style="fill:rgb(0,0,255);stroke-width:10;stroke:rgb(0,0,0)" /> 
</svg> 

After doing some research, the only way that I have found to render the SVG is this way:

<div>
  <div dangerouslySetInnerHTML={{ __html: this.state.picture }}></div>
</div>

But I'm a little confused on whether this is the preferred and flexible way to do it. If I want a button on my page where if I click it, the circle will turn red, how will I be able to do that with my current code? What about a button that will add another circle to the svg?

I know I have to access the rect in some way and change the style, but I cannot think of a way with the way I've set it up.

I tried looking for a solution but I can't seem to find one, so I'm under the impression that I have to render my SVG a different way. Could anyone help me figure this out? Thank you

I created https://github.com/hugozap/react-svgmt to facilitate SVG loading and manipulation:

You can load the SVG from a url or string and use SvgProxy to update any element using a CSS selector.

<SvgLoader width="100" height="100" path="/sample1.svg">
        <SvgProxy selector="rect" fill="red" />
</SvgLoader>

If you are interested I wrote an article about it sometime ago

https://medium.com/@hugozap/svg-manipulation-tools-for-react-e1d58b754c81

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM