SVG use tag and ReactJS

后端 未结 6 1549
慢半拍i
慢半拍i 2020-12-23 00:05

So normally to include most of my SVG icons that require simple styling, I do:


    
         


        
6条回答
  •  无人及你
    2020-12-23 00:41

    MDN says that xlink:href is deprecated in favor of href. You should be able to use the href attribute directly. The example below includes both versions.

    As of React 0.14, xlink:href is available via React as the property xlinkHref. It is mentioned as one of the "notable enhancements" in the release notes for 0.14.

    
    
      
    
    
    
    
      
    
    

    Update 2018-06-09: Added info about href vs xlink:href attributes and updated example to include both. Thanks @devuxer

    Update 3: At time of writing, React master SVG properties can be found here.

    Update 2: It appears that all svg attributes should now be available via react (see merged svg attribute PR).

    Update 1: You may want to keep an eye on the svg related issue on GitHub for additional SVG support landing. There are developments in the works.

    Demo:

    const svgReactElement = (
      
        
        { /* Deprecated xlink:href usage */ }
        
      
    );
    
    var resultHtml = ReactDOMServer.renderToStaticMarkup(svgReactElement);
    document.getElementById('render-result-html').innerHTML = escapeHtml(resultHtml);
    
    ReactDOM.render(svgReactElement, document.getElementById('render-result') );
    
    function escapeHtml(unsafe) { return unsafe.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); }
    
    
    
    
    

    Render result of rendering:

    <svg
      viewBox="0 0 1340 667"
      width="100"
      height="100"
    >
      <image width="667" height="667" href="https://i.imgur.com/w7GCRPb.png"/>
      { /* Deprecated xlink:href usage */ }
      <image width="667" height="667" x="673" xlinkHref="https://i.imgur.com/w7GCRPb.png"/>
    </svg>

    ReactDOMServer.renderToStaticMarkup() output:

    
    

    ReactDOM.render() output:

提交回复
热议问题