You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于指定对象结构生成含React.Fragment的React组件

How to Render Your Object Structure with React.Fragment

Hey there! Let's break down how to turn your object into the desired React component using React.Fragment (or its shorthand <>...</>).

First, the key idea is to iterate over your object's entries (since we need both the group number and the list of files), then render each group's heading followed by its files. React.Fragment is perfect here because it lets us return multiple sibling elements without adding an extra DOM wrapper like a <div> or <span>.

Here's a complete functional component example that does exactly what you need:

import React from 'react';

const FileList = () => {
  const obj = { 
    1: [{ row: 1, name: 'file1' }, { row: 1, name: 'file2' }], 
    2: [{ row: 2, name: 'file3' }] 
  };

  return (
    <React.Fragment>
      {Object.entries(obj).map(([groupNumber, files]) => (
        <React.Fragment key={groupNumber}>
          <h2>Element: {groupNumber}</h2>
          {files.map(file => (
            <div key={file.name}>{file.name}</div>
          ))}
        </React.Fragment>
      ))}
    </React.Fragment>
  );
};

export default FileList;

Let's walk through what's happening here:

  • Object.entries(obj): This converts your object into an array of [key, value] pairs (e.g., ['1', [{...}, {...}]]), making it easy to iterate over each group.
  • Outer React.Fragment: Wraps all the rendered groups so we can return multiple elements from the component (React requires a single root element, and Fragment avoids extra DOM nodes).
  • Inner React.Fragment with key: Each group (heading + files) needs a unique key when mapping, so we use the groupNumber here. This helps React efficiently update the DOM when changes happen.
  • File mapping: For each file in the group, we render a <div> with the file name, using file.name as the key (assuming file names are unique within their group; if not, you could use a combination like ${groupNumber}-${file.name}).

Alternatively, you can use the shorter <>...</> syntax for React.Fragment (note that you can't pass a key to the shorthand, so we still need the full React.Fragment for the inner mapped groups):

return (
  <>
    {Object.entries(obj).map(([groupNumber, files]) => (
      <React.Fragment key={groupNumber}>
        <h2>Element: {groupNumber}</h2>
        {files.map(file => (
          <div key={file.name}>{file.name}</div>
        ))}
      </React.Fragment>
    ))}
  </>
);

This will output exactly the structure you're looking for, with no extra DOM elements added by the Fragment.

内容的提问来源于stack exchange,提问作者user1595858

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:49:54