我如何选择在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样式组件是危险的,因为无论条件如何,代码块总是被执行。例如,如果banner为空,这将导致一个空异常:

//dangerous
render: function () {
  return (
    <div id="page">
      <If test={this.state.banner}>
        <img src={this.state.banner.src} />
      </If>
      <div id="other-content">
         blah blah blah...
      </div>
    </div>
  );
}

另一种选择是使用内联函数(对else语句特别有用):

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

react问题的另一个选项:

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

其他回答

还有一种技术使用渲染道具对组件进行条件渲染。它的好处是,在条件满足之前,渲染不会计算,因此不需要担心null和未定义的值。

const Conditional = ({ condition, render }) => {
  if (condition) {
    return render();
  }
  return null;
};

class App extends React.Component {
  constructor() {
    super();
    this.state = { items: null }
  }

  componentWillMount() {
    setTimeout(() => { this.setState({ items: [1,2] }) }, 2000);
  }

  render() {
    return (
      <Conditional
        condition={!!this.state.items}
        render={() => (
          <div>
            {this.state.items.map(value => <p>{value}</p>)}
          </div>
        )}
      />
    )
  }
}

这个呢?让我们定义一个简单的帮助If组件。

var If = React.createClass({
    render: function() {
        if (this.props.test) {
            return this.props.children;
        }
        else {
            return false;
        }
    }
});

然后这样用:

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

更新:随着我的答案越来越受欢迎,我觉得有义务警告你这个解决方案的最大危险。正如在另一个回答中指出的那样,无论条件是真还是假,<If />组件中的代码总是被执行。因此,如果横幅为空,下面的例子将失败(注意第二行上的属性访问):

<If test={this.state.banner}>
    <div id="banner">{this.state.banner.url}</div>
</If>

你使用它的时候一定要小心。我建议你阅读其他的(更安全的)方法。

更新2:回头看,这种方法不仅危险,而且极其繁琐。这是一个典型的例子,当一个开发人员(我)试图将他知道的模式和方法从一个领域转移到另一个领域,但它实际上不起作用(在这种情况下是其他模板语言)。

如果你需要一个条件元素,可以这样做:

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

如果你还需要else分支,只需使用三元操作符:

{this.state.banner ?
   <div id="banner">{this.state.banner}</div> :
   <div>There is no banner!</div>
}

它更短,更优雅,更安全。我一直在用它。唯一的缺点是,如果分支那么容易,你就不能做其他事情,但这通常不常见。

无论如何,这是可能的,这要感谢JavaScript中的逻辑运算符的工作方式。逻辑运算符甚至允许这样的小技巧:

<h3>{this.state.banner.title || 'Default banner title'}</h3>

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

大多数例子都只有一行“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>
  );
}

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

Ie:

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