HarmonyOS 鸿蒙Next 请问大佬,为啥我模仿官方教程做@State后面的布尔值修改不了啊

HarmonyOS 鸿蒙Next 请问大佬,为啥我模仿官方教程做@State后面的布尔值修改不了啊

@Entry
@Componentstruct Index {
  [@State](/user/State) message: string = 'Test'
  [@State](/user/State) testColor: Boolean = true;

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .fontColor(this.testColor ? Color.Blue : Color.Red)
      }
      .width('100%')
      .onClick(() => {
        this.testColor = !this.testColor;
        // this.message = '?';
        console.log(this.testColor ? 'true' : 'false');
      })
    }
    .height('100%')
  }
}

点击后,log显示testColor这个布尔值一直不变,我把[@State](/user/State)去掉后倒是可以变,但是字体颜色不变,嘤嘤嘤

有哪位大佬能帮忙解释一下吗

更多关于HarmonyOS 鸿蒙Next 请问大佬,为啥我模仿官方教程做@State后面的布尔值修改不了啊的实战教程也可以访问 https://www.itying.com/category-93-b0.html

5 回复
@State testColor : `boolean` = true;

Boolean 改为 小写 boolean

更多关于HarmonyOS 鸿蒙Next 请问大佬,为啥我模仿官方教程做@State后面的布尔值修改不了啊的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


谢谢大佬,我试试!

我也是刚学,而且没接触过js。

我感觉你这有两种方法:

一、写一个方法放进去:

[@Entry](/user/Entry)[@Componentstruct](/user/Componentstruct) Index {
  [@State](/user/State) message: string = 'Test'
  [@State](/user/State) testColor : Boolean = true; 
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .fontColor( getColor(this.testColor) )
      }
      .width('100%')
      .onClick(() => {
        this.testColor = !this.testColor;
        // this.message = '?';
        console.log(this.testColor ? 'true' : 'false');
      })
    }
    .height('100%')
  }        
  getColor(b:boolean):Color{
    return b ? Color.Blue : Color.Red    
  }
}

二、if/else渲染:

[@Entry](/user/Entry)[@Componentstruct](/user/Componentstruct) Index {
  [@State](/user/State) message: string = 'Test'
  [@State](/user/State) testColor : Boolean = true; 
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          if(this.testColor){
            .fontColor( Color.Blue )
          }else{
            .fontColor( Color.Red )
          }               
      }
      .width('100%')
      .onClick(() => {
        this.testColor = !this.testColor;
        // this.message = '?';
        console.log(this.testColor ? 'true' : 'false');
      })
    }
    .height('100%')
  }
}```

对不起,您提供的内容中没有包含任何HTML代码。请提供包含HTML代码的完整内容,以便我可以将其转换为Markdown格式。

姓名

张三

职位

软件工程师

所在地

北京

简介

资深软件开发专家,拥有超过10年的编程经验。

回到顶部