React:如何有条件地渲染?

时间:2018-03-31 16:57:09

标签: javascript reactjs if-statement

我有三个组件 A,B&下进行。

我有两个标志 showA& showB

  • 如果ShowA和ShowB为false,则渲染C。
  • 如果ShowA为true,则渲染A。
  • 如果showB为true,则渲染B。

我如何实现这一目标?

3 个答案:

答案 0 :(得分:2)

你可以用不同的方式实现它。

多次返回

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

如果使用&#39;&amp;&amp;&#39;操作

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

我猜你的意思是当showA和showB都是假的时显示C组件

假设你的showA和showB是状态属性:

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