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

当前回答

还有一个非常简洁的单行版本……{this.props.product.title || "No Title"}

Ie:

render: function() {
            return (
                <div className="title">
                    { this.props.product.title || "No Title" }
                </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})}/>
  }
})()}

在ES6中,你可以用简单的一行程序来实现

const If = ({children, show}) => show ? children : null

"show"是一个布尔值,你可以通过

<If show={true}> Will show </If>
<If show={false}> WON'T show </div> </If>

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

{ 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中进行条件渲染的方法!

我喜欢立即调用函数表达式(IIFE)和if-else的显式呈现回调和三元运算符。

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

你只需要熟悉IIFE语法,{expression}是常用的React语法,在它里面,你只需要考虑你正在编写一个调用自己的函数。

function() {

}()

需要用括号来包装

(function() {

}())

你也可以这样写

{ this.state.banner && <div>{...}</div> }

如果你的州。Banner为空或未定义,则跳过右侧的条件。