
回复
本篇将带你实现一个数字键盘应用,支持用户通过点击数字键输入数字并实时更新显示内容。我们将展示如何使用按钮组件和状态管理来实现一个简洁且实用的数字键盘。
数字键盘应用将实现以下功能:
@Entry
和 @Component
装饰器Column
和 Row
布局组件Button
组件用于实现数字键Text
组件用于显示输入的内容@State
修饰符用于状态管理NumberKeyboardApp
NumberKeyboardPage
、NumberButton
NumberKeyboardPage.ets
、Index.ets
、NumberButton.ets
// 文件名:NumberKeyboardPage.ets
import { NumberButton } from "./NumberButton";
@Component
export struct NumberKeyboardPage {
@State input: string = ''; // 显式指定类型为 string
// 定义数字按钮内容
private buttonRows: string[][] = [
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9'],
['0']
];
build() {
Column({ space: 20 }) {
// 显示当前输入
Text(`输入: ${this.input}`)
.fontSize(24)
.fontWeight(FontWeight.Bold)
.alignSelf(ItemAlign.Center);
// 使用 ForEach 遍历每一行按钮
ForEach(this.buttonRows, (row: string[]) => {
Row({ space: 10 }) {
// 遍历当前行的按钮
ForEach(row, (label: string) => {
// 使用双向绑定
NumberButton({ label: label }).onClick(() => this.input += label);
});
}
});
// 清除和删除按钮
Row({ space: 10 }) {
Button('清空')
.onClick(() => this.clearInput())
.backgroundColor(Color.Red)
.fontColor(Color.White)
.width('45%')
.alignSelf(ItemAlign.Center);
Button('删除')
.onClick(() => this.deleteLastCharacter())
.backgroundColor(Color.Gray)
.fontColor(Color.White)
.width('45%')
.alignSelf(ItemAlign.Center);
}
}
.padding(20)
.width('100%')
.height('100%')
.alignItems(HorizontalAlign.Center);
}
// 清空输入
private clearInput() {
this.input = '';
}
// 删除最后一个字符
private deleteLastCharacter() {
this.input = this.input.slice(0, -1);
}
}
// 文件名:Index.ets
import { NumberKeyboardPage } from "./NumberKeyboardPage"; // 引入 NumberKeyboardPage
@Entry
@Component
export struct Index {
build() {
Column({ space: 20 }) {
// 渲染 NumberKeyboardPage 组件
NumberKeyboardPage();
}
.padding(20)
.width('100%')
.height('100%')
.alignItems(HorizontalAlign.Center);
}
}
// 文件名:NumberButton.ets
@Component
export struct NumberButton {
@Prop label: string = ''; // 按钮标签
build() {
Button(this.label)
.backgroundColor(Color.Blue)
.fontColor(Color.White)
.width('30%')
.alignSelf(ItemAlign.Center)
.height(60);
}
}
效果示例:用户可以点击数字按钮,输入内容实时更新。点击清空按钮清除所有输入,点击删除按钮删除最后一个字符。
NumberButton
组件通过 @Prop
获取标签(数字)和父组件,点击按钮时更新父组件的输入内容。@State
管理当前输入的内容,每次点击按钮,输入的数字都会追加到 input
字符串中。clearInput
和 deleteLastCharacter
方法清除输入或删除最后一个字符。通过数字键盘的实现,用户可以学习如何使用按钮组件实现简单的用户交互,并掌握如何通过状态管理和组件间的数据传递进行动态界面更新。本应用适合初学者了解按钮交互和状态管理的基本用法。
在下一篇「UI互动应用篇20 - 闪烁按钮效果」中,我们将展示如何实现一个闪烁按钮效果。该按钮将定期改变颜色,形成闪烁的视觉效果,为用户带来动感的互动体验。
作者:SoraLuna
链接:https://www.nutpi.net/thread?topicId=376
來源:坚果派
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。