鸿蒙的@State
鸿蒙是xml和逻辑代码,用@State实则是更新内容
@State实则是刷新页面的内容
猜数字游戏源码:
@Entry
@Component
struct GuessNumberGame {private answer: number = Math.floor(Math.random() * 100) + 1private input: string = ''@State private hint: string = '请输入一个 1~100 的数字'@State private count: number = 0build() {Column({ space: 20 }) {Text('🎯 猜数字游戏').fontSize(24).fontWeight(FontWeight.Bold)TextInput({placeholder: '输入你的猜测',text: this.input,}).onChange((value: string) => {this.input = value}).width(250).height(40).backgroundColor('#F5F5F5').borderRadius(8).padding(10)Button('提交').onClick(() => {this.checkGuess()}).backgroundColor('#007DFF').fontColor(Color.White).borderRadius(8).width(120).height(40)Text(`提示:${this.hint}`).fontSize(18).fontColor('#333')Text(`你已经猜了 ${this.count} 次`).fontSize(16).fontColor('#999')}.padding(20).align(Alignment.Center)}private checkGuess() {const guess = Number(this.input)if (isNaN(guess) || guess < 1 || guess > 100) {this.hint = '请输入 1 到 100 之间的数字'return}this.count++if (guess < this.answer) {this.hint = '太小了!'} else if (guess > this.answer) {this.hint = '太大了!'} else {this.hint = `🎉 恭喜你猜对了!共用了 ${this.count} 次`}}
}