【问题标题】:React img tag issue with url and class用 url 和 class 反应 img 标签问题
【发布时间】:2014-11-21 04:00:19
【问题描述】:

我的 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);

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>

我有两个问题:

有什么想法吗?

【问题讨论】:

    标签: javascript css reactjs


    【解决方案1】:

    请记住,您的 img 并不是真正的 DOM 元素,而是 javascript 表达式。

    1. 这是一个 JSX 属性表达式。在 src 字符串表达式周围加上花括号,它将起作用。见http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions

    2. 在 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);
      

    【讨论】:

    • 如果您检查输出,您会发现 alt 属性也丢失了。 :(
    • alt 应该是 alt={"boohoo"}.
    【解决方案2】:
    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>
          );
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-07
      • 2017-07-21
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多