首页 > 解决方案 > 调整 HTML 在地图循环中的呈现位置

问题描述

我有一组要在页面上呈现的 HTML 元素,但取决于元素,我想调整它们的包装方式。

const sections = [
  {
    id: 'top',
  },
  {
    id: 'left',
  },
  {
    id: 'right',
  },
  {
    id: 'bottom',
  }
]

const Element = (props) => {
  return <div id={props.id}>hello</div>
}

const ArticleRightRail = (props) =>
  <div>
    <header>
    </header>
    <article>
      {sections.map((section, i) => <Element key={i} {...section} >hello!</Element> )}
    </article>
  </div>

在上面的示例中,我想要任何id不在标签内top或将在标签内bottom呈现的内容,以及在标签内呈现或将要呈现的<article>任何内容。使用 React 处理这种情况的最佳方法是什么?topbottom<header>

标签: reactjs

解决方案


@JamesIves,反应代码是:

const listForHeader = sections.filter((section, i) => {
    return section === "top" || section === "bottom";
});

const listForArticle = sections.filter((section, i) => {
    return section != "top" || section != "bottom";
})

const ArticleRightRail = (props) =>
  <div>
    <header>
      {listForHeader.map((section, i) => <Element key={i} {...section} >hello!</Element> )}
    </header>
    <article>
      {listForArticle.map((section, i) => <Element key={i} {...section} >hello!</Element> )}
    </article>
  </div>

推荐阅读