我如何选择在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>
    );
}

当前回答

我使用一个更显式的快捷方式:立即调用函数表达式(IIFE):

{(() => {
  if (isEmpty(routine.queries)) {
    return <Grid devices={devices} routine={routine} configure={() => this.setState({configured: true})}/>
  } else if (this.state.configured) {
    return <DeviceList devices={devices} routine={routine} configure={() => this.setState({configured: false})}/>
  } else {
    return <Grid devices={devices} routine={routine} configure={() => this.setState({configured: true})}/>
  }
})()}

其他回答

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

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

* * if - else

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

**三元运算符

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

逻辑&&运算符

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

**开关箱

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

** 枚举

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

**多级/嵌套条件渲染

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

** HOC

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

**外部模板组件

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

下面是我使用ES6的方法。

import React, { Component } from 'react';
// you should use ReactDOM.render instad of React.renderComponent
import ReactDOM from 'react-dom';

class ToggleBox extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // toggle box is closed initially
      opened: false,
    };
    // http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html
    this.toggleBox = this.toggleBox.bind(this);
  }

  toggleBox() {
    // check if box is currently opened
    const { opened } = this.state;
    this.setState({
      // toggle value of `opened`
      opened: !opened,
    });
  }

  render() {
    const { title, children } = this.props;
    const { opened } = this.state;
    return (
      <div className="box">
        <div className="boxTitle" onClick={this.toggleBox}>
          {title}
        </div>
        {opened && children && (
          <div class="boxContent">
            {children}
          </div>
        )}
      </div>
    );
  }
}

ReactDOM.render((
  <ToggleBox title="Click me">
    <div>Some content</div>
  </ToggleBox>
), document.getElementById('app'));

演示:http://jsfiddle.net/kb3gN/16688/

我使用的代码如下:

{opened && <SomeElement />}

仅当opened为true时才会呈现SomeElement。它的工作原理在于JavaScript解析逻辑条件的方式:

true && true && 2; // will output 2
true && false && 2; // will output false
true && 'some string'; // will output 'some string'
opened && <SomeElement />; // will output SomeElement if `opened` is true, will output false otherwise

由于React会忽略false,我发现它是有条件渲染某些元素的好方法。

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

当必须只渲染某些东西,如果传递的条件是完全满足的,你可以使用语法:

{ condition && what_to_render }

这种方式的代码看起来像这样:

render() {
    const { banner } = this.state;
    return (
        <div id="page">
            { banner && <div id="banner">{banner}</div> }
            <div id="other-content">
                blah blah blah...
            </div>
        </div>
    );
}

当然,还有其他有效的方法来做到这一点,这完全取决于偏好和场合。如果你感兴趣,你可以在本文中学习更多如何在React中进行条件渲染的方法!

我想这一点没有被提及。这就像你自己的答案,但我认为它更简单。您总是可以从表达式中返回字符串,并且可以在表达式中嵌套jsx,因此这允许易于阅读的内联表达式。

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

<script src="http://dragon.ak.fbcdn.net/hphotos-ak-xpf1/t39.3284-6/10574688_1565081647062540_1607884640_n.js"></script> <script src="http://dragon.ak.fbcdn.net/hphotos-ak-xpa1/t39.3284-6/10541015_309770302547476_509859315_n.js"></script> <script type="text/jsx;harmony=true">void function() { "use strict"; var Hello = React.createClass({ render: function() { return ( <div id="page"> {this.props.banner ? <div id="banner">{this.props.banner}</div> : ''} <div id="other-content"> blah blah blah... </div> </div> ); } }); var element = <div><Hello /><Hello banner="banner"/></div>; React.render(element, document.body); }()</script>