简体   繁体   English

反应:如何有条件地渲染?

[英]React: How to conditionally render?

I have three components A, B & C. 我有三个组成部分A,B和C。

I have two flags showA & showB. 我有两个标志showA和showB。

  • If ShowA and ShowB are false then render C. 如果ShowA和ShowB为false,则渲染C。
  • If ShowA is true only then render A. 如果ShowA为true,则仅渲染A。
  • If showB is true only then render B. 如果showB为true,则仅渲染B。

How do i achieve this? 我该如何实现?

You can achieve it in different ways. 您可以通过不同的方式来实现它。

Multiple returns 多次退货

render() {
    const { showA, showB } = this.state;
    if (showA) return <A />
    if (showB) return <B />
    return <C />
}

Inline if with the '&&' operator 与'&&'运算符内联

render() {
    const { showA, showB } = this.state;
    return (
        <div>
            {(showA && !showB) && <A />}
            {(showB && !showA) && <B />}
            {(!showA && !showB) && <C />}
        </div>
    )
}

See also: https://reactjs.org/docs/conditional-rendering.html 另请参阅: https : //reactjs.org/docs/conditional-rendering.html

  class APP extends React.Component {
    constructor() {
      super();
      this.state = { showA: false, showB: false };
    }

    render() {
      const {showA, showB} = this.state;
      return [showA && <A/>, showB && <B />];
   }
 }

I guess you meant show C component when showA and showB are both false 我想你的意思是showA和showB都为false时显示C组件

Assuming that your showA and showB are state properties: 假设您的showA和showB是状态属性:

render() {
  return (
    this.state.showA 
    ? <A />
    : this.state.showB ? <B />
    : <C />
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM