效果:
1、在组件库中引入序列组件后再改改:
const charCodeOfA = 'A'.charCodeAt(0) //65
const groups = Array(26).fill('').map((_, i) => ({
title: String.fromCharCode(charCodeOfA + i),
items: all.reduce((arr, item) => {
if(item.pinyin[0]){
if (item.pinyin[0].toUpperCase() == String.fromCharCode(charCodeOfA + i)) {
arr.push(item)
}
}
return arr
}, [])
}))
PS:
Array(26) [empty × 26]
Array(26).fill('') 表示empty被空字符串填充 ['', '', '', '', '']
2、渲染
<div style={{ height: window.innerHeight }}>
<IndexBar ref={indexBarRef}>
{groups.map(group => {
const { title, items } = group
return (
<IndexBar.Panel
index={title}
title={`标题${title}`}
key={`标题${title}`}
>
<List>
{items.map((item, index) => (
<List.Item key={index}>{item.name}</List.Item>
))}
</List>
</IndexBar.Panel>
)
})}
</IndexBar>
</div>
3、完整代码
import React, { useEffect, useRef, useState } from 'react'
import request from '../service/request'
import { IndexBar, List } from 'antd-mobile';
import { pinyin } from 'pinyin-pro';
export default function City() {
const [all, setAll] = useState([])
const indexBarRef = useRef(null)
const charCodeOfA = 'A'.charCodeAt(0) //65
const groups = Array(26).fill('').map((_, i) => ({
title: String.fromCharCode(charCodeOfA + i),
items: all.reduce((arr, item) => {
if (item.pinyin[0]) {
if (item.pinyin[0].toUpperCase() === String.fromCharCode(charCodeOfA + i)) {
arr.push(item)
}
}
return arr
}, [])
}))
useEffect(() => {
request.get('/getOne').then(res => {
res.data.map(item => {
item.pinyin = pinyin(item.name, { toneType: 'none' })
})
setAll(res.data)
})
}, [])
console.log(Array(5).fill(''));
return (
<div style={{ height: window.innerHeight }}>
<IndexBar ref={indexBarRef}>
{groups.map(group => {
const { title, items } = group
return (
<IndexBar.Panel
index={title}
title={`标题${title}`}
key={`标题${title}`}
>
<List>
{items.map((item, index) => (
<List.Item key={index}>{item.name}</List.Item>
))}
</List>
</IndexBar.Panel>
)
})}
</IndexBar>
</div>
)
}