List组件替换元素位置导致UI显示异常,功能类似于歌曲置顶效果,问题代码示例参考如下:
// Index.ets
import { JSON, util } from '@kit.ArkTS';
class Contact {
key: string = util.generateRandomUUID(true);
name: string;
icon: Resource;
constructor(name: string, icon: Resource) {
this.name = name;
this.icon = icon;
}
}
@Entry
@Component
struct Index {
@State private contacts: Array<Object> = [
new Contact('小明', $r("app.media.startIcon")),
new Contact('小红', $r("app.media.startIcon")),
new Contact('小黑', $r("app.media.startIcon")),
new Contact('小黄', $r("app.media.startIcon")),
new Contact('小绿', $r("app.media.startIcon")),
];
build() {
Column({ space: 10 }) {
List() {
ForEach(this.contacts, (item: Contact, index: number) => {
ListItem() {
Row() {
Image(item.icon)
.width(40)
.height(40)
.margin(10)
Text(item.name).fontSize(20)
}
.width('100%')
.justifyContent(FlexAlign.Start)
}.onClick(() => {
// 将对应位置的元素移至首位
if (this.contacts.length > 0) {
const movedItem = this.contacts.splice(index, 1);
this.contacts.unshift(movedItem)
}
})
}, (item: Contact) => JSON.stringify(item))
}
.width('100%')
}
}
} 实现类似于歌曲置顶操作,点击元素后,该元素从原位置消失但未正确显示在顶部,异常效果如下:

调试发现点击事件中代码行:this.contacts.unshift(movedItem)未能实现UI刷新,movedItem类型为Object。调试将movedItem更改为自定义class类型可以实现UI刷新。
修改参数contacts的类型为Array<Contact>,由于splice方法返回值为数组类型,而unshift的入参为数组中元素类型。因此需要取splice方法返回数组的首项值,代码修改如下:
import { JSON, util } from '@kit.ArkTS';
class Contact {
key: string = util.generateRandomUUID(true);
name: string;
icon: Resource;
constructor(name: string, icon: Resource) {
this.name = name;
this.icon = icon;
}
}
@Entry
@Component
struct Index {
@State private contacts: Array<Contact> = [
new Contact('小明', $r('app.media.startIcon')),
new Contact('小红', $r('app.media.startIcon')),
new Contact('小黑', $r('app.media.startIcon')),
new Contact('小黄', $r('app.media.startIcon')),
new Contact('小绿', $r('app.media.startIcon')),
];
build() {
Column({ space: 10 }) {
List() {
ForEach(this.contacts, (item: Contact, index: number) => {
ListItem() {
Row() {
Image(item.icon)
.width(40)
.height(40)
.margin(10)
Text(item.name).fontSize(20)
}
.width('100%')
.justifyContent(FlexAlign.Start)
}.onClick(() => {
// 将对应位置的元素移至首位
if (this.contacts.length > 0) {
const movedItem = this.contacts.splice(index, 1);
this.contacts.unshift(movedItem[0]);
}
})
}, (item: Contact) => JSON.stringify(item))
}
.width('100%')
}
}
}