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

当前回答

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

其他回答

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

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


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

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

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

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

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

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

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

还有一种技术使用渲染道具对组件进行条件渲染。它的好处是,在条件满足之前,渲染不会计算,因此不需要担心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>
        )}
      />
    )
  }
}

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

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

* * if - else

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

**三元运算符

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

逻辑&&运算符

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

**开关箱

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

** 枚举

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

**多级/嵌套条件渲染

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

** HOC

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

**外部模板组件

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