ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 概述 ## 示例 ``` // xxx.ets import emitter from '@ohos.events.emitter'; let NextID: number = 0; class ViewData { title: string; uri: Resource; color: Color = Color.Black; id: number; constructor(title: string, uri: Resource) { this.title = title; this.uri = uri this.id = NextID++; } } @Entry @Component struct Gallery2 { dataList: Array<ViewData> = [new ViewData('flower', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon'))] scroller: Scroller = new Scroller() private preIndex: number = -1 build() { Column() { Grid(this.scroller) { ForEach(this.dataList, (item: ViewData) => { GridItem() { TapImage({ uri: item.uri, index: item.id }) }.aspectRatio(1) .onClick(() => { if (this.preIndex === item.id) { return } var innerEvent = { eventId: item.id } // 选中态:黑变红 var eventData = { data: { "colorTag": 1 } } emitter.emit(innerEvent, eventData) if (this.preIndex != -1) { console.info(`preIndex: ${this.preIndex}, index: ${item.id}, black`) var innerEvent = { eventId: this.preIndex } // 取消选中态:红变黑 var eventData = { data: { "colorTag": 0 } } emitter.emit(innerEvent, eventData) } this.preIndex = item.id }) }, (item: ViewData) => JSON.stringify(item)) }.columnsTemplate('1fr 1fr') } } } @Component export struct TapImage { @State tapColor: Color = Color.Black; private index: number; private uri: Resource; onTapIndexChange(colorTag: emitter.EventData) { this.tapColor = colorTag.data.colorTag ? Color.Red : Color.Black } aboutToAppear() { //定义事件ID var innerEvent = { eventId: this.index } emitter.on(innerEvent, this.onTapIndexChange.bind(this)) } build() { Column() { Image(this.uri) .objectFit(ImageFit.Cover) .border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor }) } } } ```