【问题标题】:Render multiple React components in shorthand if condition [duplicate]如果条件[重复],则以简写形式呈现多个 React 组件
【发布时间】:2018-09-12 12:23:24
【问题描述】:

我正在尝试以简写形式呈现多个 React 组件,但它没有按预期工作。这是我的来源:

  render() {

    const isLoggedin = true; 

    return (
      <div>
        { isLoggedin ? 
            <Greeting />
            <LogoutButton /> 
          : <LoginButton />
        }
      </div>
    );
  }

如果我只使用一个组件,它可以工作(例如删除问候):

  render() {

    const isLoggedin = true; 

    return (
      <div>
        { isLoggedin ? 
            <LogoutButton /> 
          : <LoginButton />
        }
      </div>
    );
  }

有没有办法同时渲染它们?

【问题讨论】:

  • 您遇到什么错误?尝试在示例中使用多个组件将组件包装在 &lt;div&gt; 中。

标签: reactjs


【解决方案1】:

您可以使用&lt;div&gt; &lt;/div&gt; 并在那里放置一个代码块。

例如

<div>
<Greeting />
<LogoutButton /> 
</div>

【讨论】:

    【解决方案2】:

    试试这个:

    render() {
    
      const isLoggedin = true; 
    
      return (
        <div>
          { isLoggedin ? (
              <Greeting />
              <LogoutButton />
            ) : (
              <LoginButton />
            )
          }
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-17
      • 2018-08-28
      • 2017-06-25
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多