【问题标题】:Render two components from a switch statement react从 switch 语句中渲染两个组件 react
【发布时间】:2021-03-28 17:17:46
【问题描述】:

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

这是我的 switch 语句:

 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 组件。

如何渲染我的LinkButtonTypesLinkList 组件?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    你可以使用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;
      };
    

    【讨论】:

      【解决方案2】:

      除了片段问题,您应该将switchComponent 作为一个组件 调用,而不是作为一个普通函数调用。大写它(作为功能组件应该是),然后这样做:

      <div className="dash__middle">
        <SwitchComponent {...{ selectedSidebar }} />
      </div>
      

      【讨论】:

      • 你能解释一下原因吗?
      • 使用 JSX 语法来渲染组件是 React 正确的做事方式。避免 JSX 可以工作一段时间,但它很容易在以后咬你,比如如果你试图添加一些只允许在组件内部的东西(比如钩子)。
      猜你喜欢
      • 2020-11-09
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      • 2018-08-11
      • 2019-05-26
      • 2019-10-17
      • 2019-04-26
      • 2017-12-29
      相关资源
      最近更新 更多