ArkTS 登录页面事件交互完整教程

ArkTS 登录页面事件交互完整教程

一、项目介绍

本案例实现鸿蒙 ArkTS 登录页面,核心知识点:

  1. @State 状态双向绑定
  2. TextInput 输入框、密码输入类型
  3. onChange 输入监听事件
  4. Button onClick 点击事件
  5. AlertDialog 弹窗提示
  6. 简单表单校验、按钮禁用控制
  7. Column/Row 弹性布局
  8. 完整可运行代码

@Entry
@Component
struct EventDemo {
@State username: string = ""
@State password: string = ""

build() {
Column({ space: 30 }) {
Text('用户登录')
.fontSize(32)
.fontWeight(FontWeight.Bolder)
.margin({ top: 20, bottom: 30 })

TextInput({ text: this.username, placeholder: "请输入账号:" })
.width(320)
.height(52)
.borderRadius(12)
.fontSize(16)
.border({ width: 1, color: 0xcccccc })
.padding({ left: 12 })
.onChange((value: string) => {
this.username = value
})

TextInput({ text: this.password, placeholder: "请输入密码:" })
.type(InputType.Password)
.width(320)
.height(52)
.borderRadius(12)
.fontSize(16)
.border({ width: 1, color: 0xcccccc })
.padding({ left: 12 })
.onChange((value: string) => {
this.password = value
})

Row({ space: 10 }) {
Button("立即登录")
.width('45%')
.height(52)
.backgroundColor(0x007dff)
.fontSize(18)
.borderRadius(12)
.enabled(this.username.length > 0 && this.password.length > 0)
.onClick(() => {
if (this.username === "root" && this.password === "root") {
AlertDialog.show({
title: "登录成功",
message: `欢迎你,${this.username}`
})
} else {
AlertDialog.show({
title: "登录失败",
message: "用户名或者密码错误"
})
}
})

Button("清除信息")
.width('45%')
.height(52)
.backgroundColor(0x007dff)
.fontSize(18)
.borderRadius(12)
.onClick(() => {
this.username = ""
this.password = ""
})
}
.margin({ bottom: 80 })

}
.width('100%')
.height('100%')
.padding({ left: 10, right: 10 })
}
}

  1. 模拟器预览

posted @ 2026-06-18 11:41  魏旭敏m  阅读(19)  评论(0)    收藏  举报