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

当前回答

正如在回答中已经提到的,JSX为您提供了两个选项

三元运算符 {this.state.price ?< div > {this.state。价格}</div>: null} 逻辑连接 {this.state. price && <div>{this.state. price。价格}< / div >}


但是,对于price == 0,这些不适用。

JSX将在第一种情况下呈现假分支,而在逻辑连接的情况下,将不呈现任何内容。如果该属性可能为0,只需在JSX外部使用If语句即可。

其他回答

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

Ie:

render: function() {
            return (
                <div className="title">
                    { this.props.product.title || "No Title" }
                </div>
            );
        }

我最近创建了https://github.com/ajwhite/render-if,以便仅在谓词通过时安全地呈现元素。

{renderIf(1 + 1 === 2)(
  <span>Hello!</span>
)}

or

const ifUniverseIsWorking = renderIf(1 + 1 === 2);

//...

{ifUniverseIsWorking(
  <span>Hello!</span>
)}

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

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

我只是在React with TypeScript中使用了下面的代码片段

export default function ReactIf(props: {condition: boolean, children: React.ReactNode }) {
    return props.condition ? <React.Fragment>{props.children}</React.Fragment> : <React.Fragment/>;
}

实验性的ES7 do语法使这很容易。如果你正在使用Babel,启用es7。doExpressions特性然后:

render() {
  return (
    <div id="banner">
      {do {
        if (this.state.banner) {
          this.state.banner;
        } else {
          "Something else";
        }
      }}
    </div>
  );
}

见http://wiki.ecmascript.org/doku.php?id=strawman: do_expressions