HarmonyOS 开发基础(四) 子父组件双向绑定

一、知识点在代码注释里

index.ets

// 导出方式直接从文件夹
import MyInput from "../common/commons/myInput"
@Entry
@Component
/*
组件可以基于struct实现,组件不能有继承关系,struct可以比class更加快速的创建和销毁。
 */
struct Index {
  @State username :string = ""
  @State password :string = ""

  build() {
    Flex({direction:FlexDirection.Column,
      justifyContent:FlexAlign.Center,
      alignItems:ItemAlign.Center}){
      Text("登录")
        .fontSize(40)
        .fontWeight(700)

      Text(this.username)
        .fontSize(30)
        .fontWeight(700)
        .width("80%")


      // 组件封装,完成父组件向子组件传参
      MyInput({placeHolder:"请输入用户名",inputValue:$username})
      /*
         placeHolder:"请输入用户名" 实现父组件向子组件传递 :请输入用户名

         inputValue:$username   子组件把监听得到的数据传到父组件
         下列代码再使用传回来的数据
         Text(this.username)
        .fontSize(30)
        .fontWeight(700)
        .width("80%")
     该处未对数据进行校验,只是简单展示

       */
      MyInput({placeHolder:"请输密码   ",inputValue:$password})

      Button("进入app")

    }.width("100%")
     .height("100%")
     .border({width:15,color:"#000"})
  }
}

myinput.ets

/*
单独处理输入框的渲染效果
 */
@Component
struct MyInput {
  /*
  @Prop装饰的变量必须使用其父组件提供的@State变量进行初始化,
  允许组件内部修改@Prop变量,但更改不会通知给父组件,
  父组件变量的更改会同步到@prop装饰的变量,即
  @Prop属于单向数据绑定。
   */
  @Prop placeHolder :string
  /*

   */
  @Link inputValue : string
  build(){
    TextInput({placeholder:this.placeHolder,text :this.inputValue})
      // 此处为监听事件
      //https://docs.openharmony.cn/pages/v3.1/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md/
      .onChange((value:string)=>{
        this.inputValue = value
      })
      .width("80%")
      .height(40)

  }
}

//先导出
export default MyInput

二、模拟器运行演示

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值