我如何选择在JSX中包含一个元素?下面是一个使用横幅的例子,如果它已经被传入,那么它应该在组件中。我想避免的是在if语句中重复HTML标记。

render: function () {
    var banner;
    if (this.state.banner) {
        banner = <div id="banner">{this.state.banner}</div>;
    } else {
        banner = ?????
    }
    return (
        <div id="page">
            {banner}
            <div id="other-content">
                blah blah blah...
            </div>
        </div>
    );
}

当前回答

当你在"if"分支中有多个元素时,这个组件可以工作:

var Display = React.createClass({
  render: function () {
    if (!this.props.when) {
      return false;
    }
    return React.DOM.div(null, this.props.children);
  },
});

用法:

render: function() {
  return (
    <div>
      <Display when={this.state.loading}>
        Loading something...
        <div>Elem1</div>
        <div>Elem2</div>
      </Display>
      <Display when={!this.state.loading}>
        Loaded
        <div>Elem3</div>
        <div>Elem4</div>
      </Display>
    </div>
  );
}

附注:有些人认为这些组件不适合代码阅读。但在我看来,Html和javascript更糟糕

其他回答

只是添加另一个选项-如果你喜欢/容忍coffee-script,你可以使用coffee-react来编写JSX,在这种情况下,if/else语句是可用的,因为它们是coffee-script中的表达式,而不是语句:

render: ->
  <div className="container">
    {
      if something
        <h2>Coffeescript is magic!</h2>
      else
        <h2>Coffeescript sucks!</h2>
    }
  </div>  

你可以使用一个函数并返回组件,同时保持渲染函数的精简

class App extends React.Component {
  constructor (props) {
    super(props);
    this._renderAppBar = this._renderAppBar.bind(this);
  }

  render () {
    return <div>
      {_renderAppBar()}

      <div>Content</div>

    </div>
  }

  _renderAppBar () {
    if (this.state.renderAppBar) {
      return <AppBar />
    }
  }
}

你可以像这样使用三元运算符有条件地包含元素:

render: function(){

         return <div id="page">

                  //conditional statement
                  {this.state.banner ? <div id="banner">{this.state.banner}</div> : null}

                  <div id="other-content">
                      blah blah blah...
                  </div>

               </div>
}

大多数例子都只有一行“html”,是有条件呈现的。当我有多行需要有条件地呈现时,这对我来说似乎是可读的。

render: function() {
  // This will be renered only if showContent prop is true
  var content = 
    <div>
      <p>something here</p>
      <p>more here</p>
      <p>and more here</p>
    </div>;

  return (
    <div>
      <h1>Some title</h1>

      {this.props.showContent ? content : null}
    </div>
  );
}

第一个例子很好,因为我们可以有条件地呈现一些其他内容,如{this.props。showContent吗?内容:otherContent}

但如果你只是需要显示/隐藏内容,这是更好的,因为布尔值,Null和Undefined被忽略

render: function() {
  return (
    <div>
      <h1>Some title</h1>

      // This will be renered only if showContent prop is true
      {this.props.showContent &&
        <div>
          <p>something here</p>
          <p>more here</p>
          <p>and more here</p>
        </div>
      }
    </div>
  );
}

只是留下旗帜为未定义,它不包括在内。