【问题标题】:Render react component, based from other file option渲染反应组件,基于其他文件选项
【发布时间】:2020-12-01 18:35:14
【问题描述】:

我有一个 templates.js 文件,我在其中手动设置值:

export const galleries = [{name:'default'},{name:'carousel'},{name:'grid',set:true}];

如果对象包含{set:true} 我想在product.js 页面上呈现特定组件。

我在想:

const gallery = galleries.find(gallery=>gallery.set==true).name

然后渲染:

<div>
  gallery == "grid" ? (
    <Grid />
  ) : gallery == "carousel" ? (
    <Carousel />
  ) : (
    <Default />
  )
</div>

不过有点乱……

有没有更好的方法或者已经有一个包可以做到这一点?

【问题讨论】:

    标签: reactjs next.js react-component


    【解决方案1】:
    const Component = {
        grid: <Grid />,
        carousel: <Carousel />,
        default: <Default />
    }
    

    选项 1:

    渲染:

    <div>
      {Component[gallery]}
    </div>
    

    选项 2:

    我建议你验证画廊,因为 find 函数可能返回 null:

    const item = galleries.find(gallery=>gallery.set==true);
    const gallery = item ? item.name : "default";
    

    然后:

    <div>
      {Component[gallery]}
    </div>
    

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      • 2017-11-20
      • 2016-06-06
      • 2020-07-31
      相关资源
      最近更新 更多