鸿蒙的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