ForEach/LazyForEach键值生成规则是怎样的

ForEach和LazyForEach第三个参数是键值生成函数,(item: any, index: number) => string,这个函数不写,或者函数的参数item和index缺省的有什么区别。

HarmonyOS
2024-05-23 23:18:15
4170浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
koarla

键值的生成规则和itemGenerator ,keyGenerator有关

1.如果是keyGenerator这个函数缺省,此时生成规则由框架确定,生成规则为item和index拼接,(item: any, index: number) => { return index +“_”+ JSON.stringify(item); }。

2.如果keyGenerator没有缺省且未包含index,当itemGenerator中包含index,生成的规则是自定义键值与index拼接成的字符串,如(item)=>item+2 对应的键值是 index+“_”+(item+2),如果itemGenerator中未包含index,此时keyGenerator的生成规则是由开发者自定义的键值生成规则。

3.如果keyGenerator没有缺省,且包含index,此时不管itemGenerator中是否包含index,生成的键值规则都是开发者自定义的键值生成规格,框架不会对去拼接index。

参考代码:

规则2

let arr = [1, 2, 3, 4, 4]; 
     
@Entry 
@Component 
struct Index { 
@State message: string = 'Hello World'; 
  
build() { 
  Row() { 
    Column() { 
      ForEach(arr, (item) => { 
        Text(`${item}`) 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold) 
        Divider() 
      }, (item, index) => item + index) 
    } 
    .width('100%') 
  } 
  .height('100%') 
} 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

按照上述规则2,对应的键值为,‘1’,‘3’,‘5’,‘7’,‘8’。

分享
微博
QQ
微信
回复
2024-05-24 23:11:27


相关问题
HarmonyOS 混淆规则是否有问题
598浏览 • 1回复 待解决
WATCH4怎样导出在手表中生成log文件?
2872浏览 • 1回复 待解决