@State修饰的变量在运行时被修改就会触发ArkUI的局部更新,当变量为Array类型时,修改某个数组元素并不会触发,只有修改这个变量本身才会。

var arrsc: Array<Color> = [Color.GREEN, Color.BLUE, Color.BLACK, Color.GRAY, Color.RED]
var arrs: Array<String> = ['GREEN', 'BLUE', 'BLACK', 'GRAY', 'RED']

         未用@State修饰,不管怎样修改其元素或是本身,不会更新UI。

@State var currentColor: Array<Color> = [Color.WHITE, Color.WHITE, Color.WHITE, Color.WHITE, Color.WHITE]

         

            List(){
                ForEach(this.arrs,
                        itemGeneratorFunc: {
                            item: String, index: Int64 =>
                            ListItem() {
                                Text(item)
                            }.width(80.percent).height(20.percent).margin(10.percent)
                            .backgroundColor(this.currentColor[index])// 绑定颜色
                            .onClick({event=>
                            // this.currentColor[index] = this.arrsc[index] 不触发UI更新
                                this.flag = !this.flag
                                var newColors = this.currentColor // 新建newColors数组,修改其值再赋值到currentColor
                                newColors[index] = if(this.flag){
                                    this.arrsc[index]
                                }else {
                                    Color.WHITE
                                }
                                this.currentColor = newColors // 修改了currentColor数组本身,触发UI更新
                                })
                        })

            }.width(100.percent).height(100.percent).listDirection(Axis.Vertical)

        点击每个listitem单独变色,二次点击变为白色。

 

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐