在下面的示例代码中,多个组件直接关联同一个数据源,导致了冗余的组件刷新,如何优化:
@Entry
@Component
struct Index {
@State currentIndex: number = 0; // 当前选中的列表项下标
private listData: string[] = [];
aboutToAppear(): void {
for (let i = 0; i < 10; i++) {
this.listData.push(`组件 ${i}`);
}
}
build() {
Row() {
Column() {
List() {
ForEach(this.listData, (item: string, index: number) => {
ListItem() {
ListItemComponent({ item: item, index: index, currentIndex: this.currentIndex })
}
})
}
.alignListItem(ListItemAlign.Center)
}
.width('100%')
}
.height('100%')
}
}
@Component
struct ListItemComponent {
@Prop item: string;
@Prop index: number; // 列表项的下标
@Link currentIndex: number;
private sizeFont: number = 50;
isRender(): number {
console.info(`ListItemComponent ${this.index} Text is rendered`);
return this.sizeFont;
}
build() {
Column() {
Text(this.item)
.fontSize(this.isRender())// 根据当前列表项下标index与currentIndex的差值来动态设置文本的颜色
.fontColor(Math.abs(this.index - this.currentIndex) <= 1 ? Color.Red : Color.Blue)
.onClick(() => {
this.currentIndex = this.index;
})
}
}
}
本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。
上述示例中,每个ListItemComponent组件点击Text后会将当前点击的列表项下标index赋值给currentIndex,@Link装饰的状态变量currentIndex变化后,父组件Index和所有ListItemComponent组件中的Index值都会同步发生改变。然后,在所有ListItemComponent组件中,根据列表项下标index与currentIndex的差值的绝对值是否小于等于1来决定Text的颜色,如果满足条件,则文本显示为红色,否则显示为蓝色。可以通过@Watch装饰器实现精准刷新
上述代码中,ListItemComponent组件中的状态变量currentIndex使用@Watch装饰,Text组件直接关联新的状态变量color。当currentIndex发生变化时,会触发onCurrentIndexUpdate方法,在其中将表达式的运算结果赋值给状态变量color。只有color的值发生变化时,Text组件才会重新渲染
本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。