首页 > 解决方案 > 从 switch 语句中渲染两个组件 react

问题描述

目标:在 switch 语句中返回两个组件。具体来说,如何渲染我的 LinkButtonTypes&LinkList组件?

这是我的开关语句:

 const switchComponent = ({ selectedSidebar }) => {
    let component;
    switch (selectedSidebar) {
      // main dashboard components
      case "dashboard":
        component = <LinkButtonTypes setLinkType={setLinkType} /> && (
          <LinkList/>
        );
        break;
      // render editor components
      case "skins":
        component = <SkinsEditor />;
        break;

      default:
        console.log("Unknwon switch component");
    }
    return component;
  };

这是我渲染组件的地方:

<div className="dash__middle">
        {switchComponent({ selectedSidebar })}

      </div>

目前,switch 语句只呈现我的LinkButtonTypes组件。

如何渲染我的 LinkButtonTypes&LinkList组件?

标签: reactjs

解决方案


您可以使用Fragment,如下所示:

const switchComponent = ({ selectedSidebar }) => {
    let component;
    switch (selectedSidebar) {
      // main dashboard components
      case "dashboard":
        component = (
            <React.Fragment>
                <LinkButtonTypes setLinkType={setLinkType} />
                <LinkList/>
            </React.Fragment>
        );
        break;
      // render editor components
      case "skins":
        component = <SkinsEditor />;
        break;

      default:
        console.log("Unknwon switch component");
    }
    return component;
  };

推荐阅读