用url和类处理img标签问题

React img tag issue with url and class

本文关键字:img 标签 问题 处理 url      更新时间:2023-09-26

我的JSX文件中有以下简单的react代码:

/** @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);

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>

我有两个问题:

  • 图像URL呈现不正确,呈现为"http://placehold.it/400x20undefined1'
  • 我图像上的类消失了

有什么想法吗?

请记住,img实际上不是一个DOM元素,而是一个javascript表达式。

  1. 这是一个JSX属性表达式。在src字符串表达式周围放大括号,它就可以工作了。看见http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-表达式

  2. 在javascript中,class属性是使用className的引用。请参阅本节中的注释:http://facebook.github.io/react/docs/jsx-in-depth.html#react-复合材料组件

    /** @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);
    
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>
      );
    }
});