HarmonyOS自学-Day3(做个登录功能小案例)

发布时间:2023-12-28 14:31:13


文章声明???

  1. 该文章为我(有编程语言基础,非编程小白)的 HarmonyOS自学笔记,此类文章笔记我会默认大家都学过前端相关的知识
  2. 知识来源为 HarmonyOS官方文档,归纳为自己的语言与理解记录于此
  3. 不出意外的话,我大抵会 持续更新
  4. 想要了解前端开发(技术栈大致有: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})
}
文章来源:https://blog.csdn.net/Richieeea/article/details/135265312
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。