如何使用新的Image()进行反应 [英] How do I use a new Image() in react
问题描述
我试图在状态改变时保持图像不被重新加载。
下面的图像变量被传递到自定义反应组件的道具。
var img = new Image();我已经设置了src,title,desc等。
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(); I've already set the src, title, desc, etc.
所以我的问题是。
在自定义反应组件中,如何获取图像对象(现在是标题为img的道具)并将其显示在渲染函数中?
So my question is. In the custom react component, how do I take the image object (now a prop titled img) and display it in the render function?
我是已经尝试
render: function(){
return <div>{this.props.img}</div>
}
但我一直得到一个DOM元素不是React组件错误的子元素。
But I keep getting a DOM elements are not valid child of React components error.
推荐答案
我认为你要做的是创建一个新的Image类型的DOMNode并将其呈现为< div>
。如果这是对的,你正在做一些React不能做的事情。两个选项:
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:
选项1(最佳):在React组件模板中渲染图像标记
Option 1 (Best): Render the image tag in your React component template
render: function() {
return (
<div>
<img src={'url-to-your-image'} />
</div>
);
}
选项2(不太好):渲染图像作为HTML字符串实体
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()} />
);
}
希望有所帮助!
这篇关于如何使用新的Image()进行反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!