Scroller对象的 scrollToIndex 方法存在限制, 当前并不支持Scroller组件,可以替换List组件后尝试scrollToIndex文档介绍:https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-container-scroll-0000001815927632\#ZH-CN\_TOPIC\_0000001815927632\_\_scrolltoindex经过测试List组件可以实现scrollToIndex 方法,参考下面demo:@Entry @Component struct Index { @State currentTabIndex: number = -1 scroller: Scroller = new Scroller(); controller: HelloComponentController = new HelloComponentController(this.scroller) build() { Column() { Stack() { HelloComponent({ controller: this.controller }) Button('父组件调用scroller').height(100).onClick(() => { // 方式一 // this.controller?.scrollToIndex(2) // 方式二 this.controller?.scroller.scrollToIndex(2) }) } .align(Alignment.TopStart) } } } class HelloComponentController { scroller: Scroller = new Scroller() constructor(scroller: Scroller) { this.scroller = scroller } // 父组件使用scroller方法 scrollTo(xOffset: number | string, yOffset: number | string) { this.scroller?.scrollTo({ xOffset, yOffset }) console.log('触发了scrollTo!!!') } scrollToIndex(value: number, smooth?: boolean, align?: ScrollAlign) { this.scroller?.scrollToIndex(value, smooth, align) console.log('触发了scrollToIndex!!!') } } @Component export struct HelloComponent { controller?: HelloComponentController private arr: ResourceColor[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue] build() { Row() { Stack() { List({ scroller: this.controller?.scroller }) { ForEach(this.arr, (item: ResourceColor) => { ListItem() { Row().backgroundColor(item).width('100%').height(200) } }, (item: string) => item) } .scrollBar(BarState.Off) // 滚动条常驻显示 .scrollBarWidth(0) // 滚动条宽度 .friction(0.6) .edgeEffect(EdgeEffect.None) Button('子组件触发').height(100).onClick(() => { this.controller?.scroller.scrollToIndex(3) }) .position({ y: 200 }) } .align(Alignment.TopStart) } .width('100%') } }
Scroller对象的 scrollToIndex 方法存在限制, 当前并不支持Scroller组件,可以替换List组件后尝试scrollToIndex
文档介绍:
https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-container-scroll-0000001815927632\#ZH-CN\_TOPIC\_0000001815927632\_\_scrolltoindex
经过测试List组件可以实现scrollToIndex 方法,参考下面demo: