import { YTabEntity } from './YTabEntity'
@Component
export struct YTabBar {
scroller: Scroller = new Scroller()
@State selectIndex: number = 0
@Require @Prop tabData: Array<YTabEntity> = []
@Prop tabHeight: Length = 44
@Prop tabSpace:number|string = 28
@Prop color: ResourceColor = "#333333"
@Prop selectColor: ResourceColor = "#1689FF"
@Prop onTabSelect:(index:number)=>void
build() {
List({ scroller: this.scroller,space:this.tabSpace }) {
ForEach(this.tabData, (item: YTabEntity, index: number) => {
ListItem() {
Column() {
Text(item.showText)
.fontColor(this.selectIndex === index ? this.selectColor : this.color)
.fontWeight(this.selectIndex === index ? FontWeight.Medium : FontWeight.Regular)
.fontSize(16)
.textAlign(TextAlign.Center)
.layoutWeight(1)
.onAreaChange((oldValue: Area, newValue: Area) => {
item.textWidth = Number.parseInt(newValue.width.toString())
console.info(`Ace: on area change, oldValue is${index} ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`)
})
Shape()
.width(item.textWidth ?? 36)
.height(2)
.borderRadius(2)
.backgroundColor(this.selectColor)
.visibility(this.selectIndex === index ? Visibility.Visible : Visibility.Hidden)
}.height('100%')
.padding({ top: 6 })
}.height('100%')
.onClick(()=>{
this.selectIndex = index
// this.onTabSelect(index)
const nextIndex = index+1
if (nextIndex<this.tabData.length) {
this.scroller.scrollToIndex(nextIndex,true,ScrollAlign.END)
}
})
})
}.height(this.tabHeight)
.listDirection(Axis.Horizontal)
.scrollBar(BarState.Off)
}
}
如何把这个List item的点击事件回调给上一级
可以定义一个controller类,在controller类中定义和子组件中类型相同的方法,在子组件中将实际封装的方法给到controller。
父组件在使用时,new一个controller对象然后转入子类中,在父组件中调用controller对应的方法即可