harmonyOS arkts 简单封装输入框(子组件调用父组件的方法)

本文介绍了作者如何在鸿蒙系统中自定义一个简单的input组件,添加图标并实现双向数据绑定,同时探讨了如何正确地在子组件间传递@Link属性和绑定方法。
摘要由CSDN通过智能技术生成

鸿蒙的UI组件功能很少,这里我自己简单封装一个input组件,只是多了一个icon,具体功能还需后续慢慢优化。这里只是熟悉下arkts封装思路。

input组件代码:
@Component
export struct searchInput {
  @Link searchText: string
  searchConfirm: () => void
  build() {
    Row() {
      Row() {
        Image($r('app.media.axchat_search')).width(20).margin({left: 10})
      }
      .borderRadius({topLeft: 8, bottomLeft: 8})
      .height(50)
      .backgroundColor('#fff')
      .alignItems(VerticalAlign.Center)
      .justifyContent(FlexAlign.Center)

      TextInput({placeholder: '搜索'})
        .height(50)
        .borderRadius({topRight: 8, bottomRight: 8})
        .backgroundColor('#fff')
        .margin({bottom: 20})
        .layoutWeight(1)
        .onChange((value) => {
          this.searchText = value
        })
        .enterKeyType(EnterKeyType.Next)
        .onSubmit(() => {
          // 搜索
          this.searchConfirm()
        })
    }.alignItems(VerticalAlign.Top)
  }
}
效果:

这里定义了searchText为输入的值,双向绑定的

接受调用组件的方法searchConfirm

使用:

@State searchValue: string = ''

// 回调的方法
searchConfirmFn() {
    
}

// 搜索输入框
searchInput({ searchText: $searchValue, searchConfirm: this.searchConfirmFn.bind(this) })
     

tip:

1. 子组件接受的@link在传值的时候需要使用$

2. 传递的方法需要使用bind改变this指向,不然会报错:is not callable

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值