HarmonyOS Grid组件使用ForEach网格布局,Ui数据更新问题

Grid组件使用ForEach网格布局,

@State 修饰数据源数组,@State positiveReviewsArr: EvaluationResult[] = []

当点击item后需要实现当前Item变色,实际情况是不会变,但是断点看选中标志变量已经改变;

或者我这种实现不合适,希望能提供一个能用的方案。

实现效果:点击item后要高亮,再次点击则需要取消高亮,最后还要收集已选选项,要上传给服务器使用

HarmonyOS
2024-08-04 14:11:38
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
milchcow

可以用以下demo实现:

class ProductInfo{ 
  public   id:string 
  public   productName:string 
  constructor( id:string,productName:string) { 
    this.id = id 
    this.productName = productName 
  } 
} 
@Entry 
@Component 
struct GridHighLight { 
  @State services: ProductInfo[] =  [ 
    new ProductInfo( '1',  'String1'), 
    new ProductInfo( '2',  'String2'), 
    new ProductInfo( '3',  'String3'), 
    new ProductInfo( '4',  'String4'), 
 
  ]; 
  @State clickStatus:Boolean = false 
  clickThings: Array<string> = [] 
  @Provide selectIndexList: Array<string> = [] 
 
 
  build() { 
    Column() { 
      Grid() { 
        ForEach(this.services, (item: ProductInfo, index) => { 
          GridItem() { 
            ToDoItem({ content: item.productName,selectIndex: item.id }) 
          } 
        }, (item: string): string => item) 
      } 
      .columnsTemplate('1fr 1fr 1fr') 
      .columnsGap(10) 
      .rowsGap(10) 
      .width('90%') 
      .backgroundColor(0xFAEEE0) 
      .height(300) 
      Text('选中的') 
      Text(`${this.selectIndexList}`) 
 
    } 
  } 
} 
@Component 
export default struct ToDoItem { 
  private content?: string; 
  @State isComplete: boolean = false; 
  private selectIndex?:string; 
  @Consume selectIndexList: Array<string> 
 
  build() { 
    Row() { 
      Column() { 
        Text(this.content).fontColor('#FFFFFF') 
      } 
      .width('30%') 
      .height(100) 
      .backgroundColor(this.isComplete ? Color.Red : Color.Blue) 
      .justifyContent(FlexAlign.Center) 
      .width('100%') 
      .height(60) 
      .onClick(() => { 
        this.isComplete = !this.isComplete; 
        if(this.selectIndex){ 
          if(this.isComplete){ 
            this.selectIndexList.push(this.selectIndex) 
          }else{ 
            let index =  this.selectIndexList.indexOf(this.selectIndex) 
            if(index !== -1){ 
              this.selectIndexList.splice(index,1) 
            } 
          } 
        } 
      }) 
    } 
  } 
}
分享
微博
QQ
微信
回复
2024-08-05 11:55:00
相关问题
【急】鸿蒙UI界面网格布局怎么设置?
16040浏览 • 4回复 待解决
HarmonyOS Grid容器视图更新问题
152浏览 • 1回复 待解决
卡片数据更新问题求大佬解答
4947浏览 • 1回复 待解决
HarmonyOS UI布局问题
103浏览 • 1回复 待解决
修改ForEach使用数据对象,UI不刷新
767浏览 • 1回复 待解决
HarmonyOS使用Refresh下拉刷新问题
232浏览 • 1回复 待解决
grid组件数据懒加载
598浏览 • 1回复 待解决
Grid组件性能问题有哪些?
130浏览 • 1回复 待解决
HarmonyOS 页面跳转刷新问题
146浏览 • 1回复 待解决
HarmonyOS 列表刷新问题
172浏览 • 1回复 待解决
HarmonyOS List item 刷新问题
234浏览 • 1回复 待解决
使用Grid 组件实现选座场景
571浏览 • 1回复 待解决
NativeWindowFlushBuffer接口刷新问题
1639浏览 • 1回复 待解决
关于Grid容器和WaterFlow使用上的问题
605浏览 • 1回复 待解决