Javascript 使用 url 和 class 反应 img 标签问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26054512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React img tag issue with url and class
提问by Serge van den Oever
I have the following simple react code in my JSX file:
我的 JSX 文件中有以下简单的反应代码:
/** @jsx React.DOM */
var Hello = React.createClass({
render: function() {
return <div><img src='http://placehold.it/400x20&text=slide1' alt={event.title} class="img-responsive"/><span>Hello {this.props.name}</span></div>;
}
});
React.renderComponent(<Hello name="World" />, document.body);
The output in the DOM is as follows:
DOM中的输出如下:
<div data-reactid=".0">
<img src="http://placehold.it/400x20undefined1" data-reactid=".0.0">
<span data-reactid=".0.1">
<span data-reactid=".0.1.0">Hello </span>
<span data-reactid=".0.1.1">World</span>
</span>
</div>
I have two issues with it:
我有两个问题:
- The image URL is rendered incorrectly, it is rendered as 'http://placehold.it/400x20undefined1'
- The class on my image disappears
- 图像 URL 呈现不正确,呈现为“ http://placehold.it/400x20undefined1”
- 我图片上的班级消失了
Any ideas?
有任何想法吗?
回答by rowbare
Remember that your img is not really a DOM element but a javascript expression.
请记住,您的 img 并不是真正的 DOM 元素,而是一个 javascript 表达式。
This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions
In javascript, the class attribute is reference using className. See the note in this section: http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components
/** @jsx React.DOM */ var Hello = React.createClass({ render: function() { return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>; } }); React.renderComponent(<Hello name="World" />, document.body);
这是一个 JSX 属性表达式。在 src 字符串表达式周围放置花括号,它将起作用。见http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions
在 javascript 中,class 属性是使用 className 引用的。请参阅本节中的注释:http: //facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components
/** @jsx React.DOM */ var Hello = React.createClass({ render: function() { return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>; } }); React.renderComponent(<Hello name="World" />, document.body);
回答by kadzielawa konrad
var Hello = React.createClass({
render: function() {
return (
<div className="divClass">
<img src={this.props.url} alt={`${this.props.title}'s picture`} className="img-responsive" />
<span>Hello {this.props.name}</span>
</div>
);
}
});

