目录
- 文章声明⭐⭐⭐
- 让我们开始今天的学习吧!
- 登录功能小案例
文章声明⭐⭐⭐
- 该文章为我(有编程语言基础,非编程小白)的 HarmonyOS自学笔记,此类文章笔记我会默认大家都学过前端相关的知识
- 知识来源为 HarmonyOS官方文档,归纳为自己的语言与理解记录于此
- 不出意外的话,我大抵会 持续更新
- 想要了解前端开发(技术栈大致有:Vue2/3、微信小程序、uniapp、HarmonyOS、NodeJS、Typescript)与Python的小伙伴,可以关注我!谢谢大家!
让我们开始今天的学习吧!
登录功能小案例
样式大致如下:
需求为:
- 实时显示用户输入的用户名和密码
- 使用 @Builder 来封装一行提示标签与输入框
- 点击登录即输出用户名与密码
- 点击重置则清空用户名和密码
代码如下:
@Entry
@Component
struct Index {// 输入框前的提示userLabel:string = '用户名';passwordLabel:string = '密码';// 用户名和密码的状态变量@State userName:string = '';@State password:string = '';// 输入框为了实现双向绑定而创建的回调函数inputCallBack=(labelName:string,newValue:string)=>{if (labelName === this.userLabel) {this.userName = newValue;} else {this.password = newValue;}}build() {Row() {Column() {inputLabel({labelName:this.userLabel,value:this.userName,callBack:this.inputCallBack})inputLabel({labelName:this.passwordLabel,value:this.password,callBack:this.inputCallBack})Row(){Button('登录').margin({right:30}).onClick(()=>{// 输出用户名和密码console.log(this.userName);console.log(this.password);})Button('重置').onClick(()=>{// 清空用户名和密码this.userName = '';this.password = '';})}}.width('100%')}.height('100%')}
}// 组件构建函数
@Builder function inputLabel($$:{labelName:string,value:string,callBack:(labelName,newValue)=>void}){Row() {// 输入框前的提示Text($$.labelName).fontSize(30).margin({ right: 20 })TextInput({text:$$.value}).width(200).onChange((newValue:string)=>{// 因为不可以直接更改父组件状态变量的值,所以选择将新的值回调给父组件让其自行更改$$.callBack($$.labelName,newValue)})}.margin({ bottom: 10 })Divider().margin({bottom:10})
}