条件关闭标签ReactJS

时间:2019-02-28 16:58:58

标签: javascript reactjs

我有这种json响应:

{id: 1, name: a}
{id: 2, name: b}
{id: 3, name: c}
{id: 4, name: d}
{id: 5, name: e}
{id: 6, name: f}

我想像这样在我的React组件中将它们按2分组:

        <div className="group-item">
          <div className="item">a</div>
          <div className="item">b</div>
        </div>
        <div className="group-item">
          <div className="item">c</div>
          <div className="item">d</div>
        </div>

等...

我尝试了此操作,但是我不知道如何有条件地关闭标签:

return _.map(items, (item, i) => {
   let groupStart, groupEnd;
   i % 2 === 0 ? groupStart = <div className="group-item"> : groupEnd = </div>
    return (
        groupStart + item.name + groupEnd
    );
});

您是否有一些技巧来实现这一目标?

3 个答案:

答案 0 :(得分:4)

您可以简单地对数据进行预处理并先进行分组,然后再呈现

,而不是有条件地关闭标签
const data = [
  {id: 1, name: 'a'},
  {id: 2, name: 'b'},
  {id: 3, name: 'c'},
  {id: 4, name: 'd'},
  {id: 5, name: 'e'},
  {id: 6, name: 'f'}
];

const res = data.reduce((acc, item, index) => {
  if(index % 2 == 0) {
    acc.push([item])
  } else {
    acc[Math.floor(index/2)].push(item);
  }
  return acc;
}, [])


return _.map(res, (item, i) => {
   return (
     <div className="group-item" key={i}>
         <div>{item[0].name}</div>
         <div>{item[1].name}</div>
     </div>
});

答案 1 :(得分:1)

由于您已经在使用lodash,所以还有_.chunk可以用来在渲染项目之前对它们进行分组:

return _.map(_.chunk(items, 2), ([first, second], i) => (
    <div className="group-item" key={i}>
        <div>{first.name}</div>
        <div>{second.name}</div>
    </div>
))

Edit ojnk5ow5pz

答案 2 :(得分:0)

您的代码很好。但这只是缺少项目包装器。根据您的评论,应该通过渲染钩子之外的函数将其循环:

const renderGroupElements = (items) => {
    return _.map(items, (item, i) => {
       let groupStart, groupEnd;
       i % 2 === 0 ? groupStart = <div className="group-item"> : groupEnd = </div>
        return (
            groupStart + <div className="item">{item.name}</div> + groupEnd
        );
    });
}
// And inside the render hook:
{ renderGroupElements(items) }