我如何选择在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组件的React:

var Node = require('react-if-comp');
...
render: function() {
    return (
        <div id="page">
            <Node if={this.state.banner}
                  then={<div id="banner">{this.state.banner}</div>} />
            <div id="other-content">
                blah blah blah...
            </div>
        </div>
    );
}

其他回答

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

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>
}

只是添加另一个选项-如果你喜欢/容忍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>  

这是一篇关于React中所有条件渲染的不同选项的文章。

何时使用哪种条件渲染的关键要点:

* * if - else

最基本的是条件渲染吗 初学者友好 使用if可以通过返回null提早退出渲染方法

**三元运算符

在if-else语句外使用它 它比if-else更简洁

逻辑&&运算符

当三元操作的一侧返回null时使用它

**开关箱

详细的 只能内联自调用函数 避免使用枚举

** 枚举

完美地映射不同的州 完美地映射不止一个条件

**多级/嵌套条件渲染

为了可读性,避免使用它们 将组件拆分为具有自己的简单条件呈现的更轻量级的组件 使用的

** HOC

使用它们来屏蔽条件呈现 组件可以专注于它们的主要用途

**外部模板组件

避免使用它们,熟悉JSX和JavaScript

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

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 />
    }
  }
}

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