如何复用代码实现带分组的React列表.map渲染?
避免重复代码实现分组列表渲染的方案
核心思路:抽离可复用组件
把重复的渲染逻辑封装成独立组件,通过传入不同配置(分组标题、列表数据、激活态管理)实现复用,彻底告别复制粘贴。
步骤1:创建可复用的侧边栏菜单组件
新建SidebarMenu.jsx(或.tsx)文件,将通用渲染逻辑封装进去:
import { Link } from 'react-router-dom'; export default function SidebarMenu({ title, items, activeIndex, onSetActiveIndex }) { return ( <div className="sidebarMenu"> <h3 className="sidebarTitle">{title}</h3> <ul className="sidebarList"> {items.map((item, index) => { const Icon = item.icon; return ( <Link to={item.to} className="link" key={index}> <li onClick={() => onSetActiveIndex(index)} className={`sidebarListItem ${index === activeIndex ? "active" : ""}`} > <Icon className="sidebarIcon"/> {item.name} </li> </Link> ); })} </ul> </div> ); }
步骤2:调整父组件的状态与渲染逻辑
原单个activeIndex无法区分不同分组的激活状态,改用对象存储各分组的激活索引,再调用封装好的组件:
import { useState } from 'react'; import SidebarMenu from './SidebarMenu'; // 导入你的列表数据和图标组件 import { DashboardListItems, QuickMenuListItems } from './your-data-file'; function Sidebar() { // 用对象管理不同分组的激活索引 const [activeIndices, setActiveIndices] = useState({ dashboard: 0, quickMenu: 0 }); // 封装更新激活索引的方法,区分不同分组 const handleSetActiveIndex = (group, index) => { setActiveIndices(prev => ({ ...prev, [group]: index })); }; return ( <div className="sidebar"> {/* 渲染Dashboard分组 */} <SidebarMenu title="Dashboard" items={DashboardListItems} activeIndex={activeIndices.dashboard} onSetActiveIndex={(index) => handleSetActiveIndex('dashboard', index)} /> {/* 渲染QuickMenu分组 */} <SidebarMenu title="Quick Menu" items={QuickMenuListItems} activeIndex={activeIndices.quickMenu} onSetActiveIndex={(index) => handleSetActiveIndex('quickMenu', index)} /> </div> ); } export default Sidebar;
可选优化:统一分组数据结构
如果后续要新增更多分组,可将所有分组信息整合到一个数组,通过循环批量渲染组件:
// 统一管理所有分组配置 const sidebarGroups = [ { title: "Dashboard", key: "dashboard", items: DashboardListItems }, { title: "Quick Menu", key: "quickMenu", items: QuickMenuListItems } ]; // 父组件中循环渲染 return ( <div className="sidebar"> {sidebarGroups.map(group => ( <SidebarMenu key={group.key} title={group.title} items={group.items} activeIndex={activeIndices[group.key]} onSetActiveIndex={(index) => handleSetActiveIndex(group.key, index)} /> ))} </div> );
后续新增分组只需在sidebarGroups数组中添加配置,无需修改渲染逻辑。
内容的提问来源于stack exchange,提问作者sultan.h
相关产品推荐
相关产品推荐

