How do I use a new Image() in react

后端 未结 2 1048
慢半拍i
慢半拍i 2021-01-11 15:08

I am trying to keep an image from reloading when the state changes. The below image variable is passed into the props of a custom react component.
var img = new Image();

相关标签:
2条回答
  • 2021-01-11 15:21

    I think what you're trying to do is create a new DOMNode of the Image variety and render that as a child of the <div>. If that's right, you're doing something React isn't made to do. Two options:

    Option 1 (Best): Render the image tag in your React component template

    render: function() {
        return (
            <div>
                <img src={'url-to-your-image'} />
            </div>
        );
    }
    

    Option 2 (Not as good): Render the image as an HTML string entity

    renderHTML: function() {
        return {
            __html : '<img src="url-to-your-image" />'
        }
    },
    
    render: function() {
        return (
            <div dangerouslySetInnerHTML={this.renderHTML()} />
        );
    }
    

    Hope that helps!

    0 讨论(0)
  • 2021-01-11 15:42

    The Image constructor returns an HTMLImageElement interface.

    So to render your img prop, which as you mention was created using var img = new Image(), you basically have to create an element and render it.

    You can do this via JSX

    const YourComponent = ({img}) => <img src={img.src} alt="foo" />
    

    or

    Use the React.CreateElement syntax if you need to do it programmatically.

    const YourComponent = ({img}) => {
    
      const myImage = React.createElement("img", {
         src: img.src,
         // any other image attributes you need go here
      }, null);
    
      return (
        {myImage}
      );
    }
    
    
    0 讨论(0)
提交回复
热议问题