如何在React中将单个动态列表按首字母拆分为多个独立列表
解决方案
先对原始列表按条目标题的首字母做分组处理,再遍历分组后的结果渲染对应<ul>结构即可,参考代码如下:
1. 数据分组逻辑
const groupedList = list.reduce((result, currentItem) => { // 取标题首字符,统一转为大写,不需要区分大小写可删除toUpperCase() // 兼容空标题场景,空标题会被归类到#分组下,不需要可以去掉兼容逻辑 const firstLetter = currentItem.title?.[0]?.toUpperCase() || '#' if (!result[firstLetter]) { result[firstLetter] = [] } result[firstLetter].push(currentItem) return result }, {})
2. 组件渲染逻辑
替换你原来的渲染代码为以下内容即可:
{/* 如需按首字母排序,可在entries后加.sort((a,b) => a[0].localeCompare(b[0])) */} {Object.entries(groupedList).map(([letter, itemList]) => ( <ul key={letter}> {itemList.map((item) => ( <li key={item.id ?? item.title}> {item.title} </li> ))} </ul> ))}
内容的提问来源于stack exchange,提问作者Tamara
相关产品推荐
相关产品推荐

