当前位置:   article > 正文

鸿蒙HarmonyOS实战-ArkTS语言(渲染控制)_unction return type inference is limited (arkts-no

unction return type inference is limited (arkts-no-implicit-return-types)

 前言

编程语言中都有自己基本的控制结构,它们在程序设计中起到了非常重要的作用。以下是几个原因:

分支控制: 在程序执行过程中,有时需要根据不同的条件分支来执行不同的代码逻辑。if/else结构通过判断条件来决定程序如何执行,实现了程序的分支控制。

数据迭代: 在程序中,需要对一些数据进行遍历、操作或者计算。ForEach和LazyForEach提供了一种便捷的方法,可以针对数据集合进行遍历,并对其中的每个元素执行特定操作。

惰性计算: 在某些情况下,程序中需要对大量的数据进行遍历或计算。LazyForEach可以实现惰性计算,只在需要时才计算相应的结果,避免了程序在运行时不必要的计算,从而提高程序效率。

一、ArkTS语言渲染控制

ArkTS是一种基于TypeScript的编程语言,支持对渲染过程进行控制和调整。以下是ArkTS语言中实现渲染控制的三个关键组件:

  1. if/else:if/else结构可以用于根据条件控制是否渲染某些元素。例如,可以通过if/else语句来实现某些物体在特定场景或条件下的显示或隐藏。

  2. ForEach:ForEach是一个迭代方法,能够遍历数组、对象等数据结构中的元素,并在渲染过程中对它们进行控制。例如,可以使用ForEach在场景中定位并控制多个物体的位置、尺寸、颜色等属性。

  3. LazyForEach:与普通ForEach不同,LazyForEach是一个惰性迭代方法,它只在需要迭代数据时才进行计算。这使得LazyForEach在处理大型数据集时更加高效,可以减少渲染时间和资源占用。

通过这些关键组件,ArkTS语言可以实现灵活、高效的渲染控制,帮助开发人员实现各种复杂的渲染效果和场景呈现。

1.if/else:条件渲染

1.1 变化规则

If/else是一种在程序中用于控制流程的结构。它包括一个if语句和一个可选的else语句。if语句表示如果条件成立,那么就执行一段代码,否则跳过该代码;else语句表示如果条件不成立,那么就执行另一段代码。这种结构允许程序根据不同的条件执行不同的操作,从而实现更灵活的程序控制。

1.2 使用场景

1.2.1 使用if进行条件渲染
  1. @Entry
  2. @Component
  3. struct ViewA {
  4. @State count: number = 0;
  5. build() {
  6. Column() {
  7. Text(`count=${this.count}`)
  8. if (this.count > 0) {
  9. Text(`count is positive`)
  10. .fontColor(Color.Green)
  11. }
  12. Button('increase count')
  13. .onClick(() => {
  14. this.count++;
  15. })
  16. Button('decrease count')
  17. .onClick(() => {
  18. this.count--;
  19. })
  20. }
  21. }
  22. }
1.2.2 使用if/else进行条件渲染
  1. @Component
  2. struct CounterView {
  3. @Link counter: number;
  4. label: string = 'unknown';
  5. build() {
  6. Row() {
  7. Text(`${this.label}`)
  8. Button(`counter ${this.counter} +1`)
  9. .onClick(() => {
  10. this.counter += 1;
  11. })
  12. }
  13. }
  14. }
  15. @Entry
  16. @Component
  17. struct MainView {
  18. @State toggle: boolean = true;
  19. @State counter: number = 0;
  20. build() {
  21. Column() {
  22. if (this.toggle) {
  23. CounterView({ counter: $counter, label: 'CounterView #positive' })
  24. } else {
  25. CounterView({ counter: $counter, label: 'CounterView #negative' })
  26. }
  27. Button(`toggle ${this.toggle}`)
  28. .onClick(() => {
  29. this.toggle = !this.toggle;
  30. })
  31. }
  32. }
  33. }
1.2.3 嵌套if语句
  1. @Entry
  2. @Component
  3. struct CompA {
  4. @State toggle: boolean = false;
  5. @State toggleColor: boolean = false;
  6. build() {
  7. Column() {
  8. Text('Before')
  9. .fontSize(15)
  10. if (this.toggle) {
  11. Text('Top True, positive 1 top')
  12. .backgroundColor('#aaffaa').fontSize(20)
  13. // 内部if语句
  14. if (this.toggleColor) {
  15. Text('Top True, Nested True, positive COLOR Nested ')
  16. .backgroundColor('#00aaaa').fontSize(15)
  17. } else {
  18. Text('Top True, Nested False, Negative COLOR Nested ')
  19. .backgroundColor('#aaaaff').fontSize(15)
  20. }
  21. } else {
  22. Text('Top false, negative top level').fontSize(20)
  23. .backgroundColor('#ffaaaa')
  24. if (this.toggleColor) {
  25. Text('positive COLOR Nested ')
  26. .backgroundColor('#00aaaa').fontSize(15)
  27. } else {
  28. Text('Negative COLOR Nested ')
  29. .backgroundColor('#aaaaff').fontSize(15)
  30. }
  31. }
  32. Text('After')
  33. .fontSize(15)
  34. Button('Toggle Outer')
  35. .onClick(() => {
  36. this.toggle = !this.toggle;
  37. })
  38. Button('Toggle Inner')
  39. .onClick(() => {
  40. this.toggleColor = !this.toggleColor;
  41. })
  42. }
  43. }
  44. }

2.ForEach:循环渲染

2.1 变化规则

ForEach是一个数组方法,用于执行一些操作,例如对数组中的每个元素执行一些代码,或者将每个元素转换为新的数组。它可以接收一个回调函数作为参数,该函数将在数组的每个元素上执行一次。在每次调用回调函数时,都会向其传递当前元素的值、索引和整个数组。该方法不会更改原始数组,而是返回一个新的、由回调函数返回的数组。

ForEach接口描述:

  1. ForEach(
  2. arr: Array,
  3. itemGenerator: (item: Array, index?: number) => void,
  4. keyGenerator?: (item: Array, index?: number): string => string
  5. )

注意点keyGenerator为键值生成函数,可以达到去重的效果:
在这里插入图片描述

  1. @Entry
  2. @Component
  3. struct Parent {
  4. @State simpleList: Array<string> = ['one', 'two', 'two', 'three'];
  5. build() {
  6. Row() {
  7. Column() {
  8. ForEach(this.simpleList, (item: string) => {
  9. ChildItem({ item: item })
  10. }, (item: string) => item)
  11. }
  12. .width('100%')
  13. .height('100%')
  14. }
  15. .height('100%')
  16. .backgroundColor(0xF1F3F5)
  17. }
  18. }
  19. @Component
  20. struct ChildItem {
  21. @Prop item: string;
  22. build() {
  23. Text(this.item)
  24. .fontSize(50)
  25. }
  26. }

执行结果
在这里插入图片描述

2.2 使用场景

2.2.1 数据源不变
  1. @Entry
  2. @Component
  3. struct ArticleList {
  4. @State simpleList: Array<number> = [1, 2, 3, 4, 5];
  5. build() {
  6. Column() {
  7. ForEach(this.simpleList, (item: string) => {
  8. ArticleSkeletonView()
  9. .margin({ top: 20 })
  10. }, (item: string) => item)
  11. }
  12. .padding(20)
  13. .width('100%')
  14. .height('100%')
  15. }
  16. }
  17. @Builder
  18. function textArea(width: number | Resource | string = '100%', height: number | Resource | string = '100%') {
  19. Row()
  20. .width(width)
  21. .height(height)
  22. .backgroundColor('#FFF2F3F4')
  23. }
  24. @Component
  25. struct ArticleSkeletonView {
  26. build() {
  27. Row() {
  28. Column() {
  29. textArea(80, 80)
  30. }
  31. .margin({ right: 20 })
  32. Column() {
  33. textArea('60%', 20)
  34. textArea('50%', 20)
  35. }
  36. .alignItems(HorizontalAlign.Start)
  37. .justifyContent(FlexAlign.SpaceAround)
  38. .height('100%')
  39. }
  40. .padding(20)
  41. .borderRadius(12)
  42. .backgroundColor('#FFECECEC')
  43. .height(120)
  44. .width('100%')
  45. .justifyContent(FlexAlign.SpaceBetween)
  46. }
  47. }

执行效果:
在这里插入图片描述

2.2.2 数据源数组项发生变化
  1. @Entry
  2. @Component
  3. struct ArticleListView {
  4. @State isListReachEnd: boolean = false;
  5. @State articleList: Array<Article> = [
  6. new Article('001', '第1篇文章', '文章简介内容'),
  7. new Article('002', '第2篇文章', '文章简介内容'),
  8. new Article('003', '第3篇文章', '文章简介内容'),
  9. new Article('004', '第4篇文章', '文章简介内容'),
  10. new Article('005', '第5篇文章', '文章简介内容'),
  11. new Article('006', '第6篇文章', '文章简介内容')
  12. ]
  13. loadMoreArticles() {
  14. this.articleList.push(new Article('007', '加载的新文章', '文章简介内容'));
  15. }
  16. build() {
  17. Column({ space: 5 }) {
  18. List() {
  19. ForEach(this.articleList, (item: Article) => {
  20. ListItem() {
  21. ArticleCard({ article: item })
  22. .margin({ top: 20 })
  23. }
  24. }, (item: Article) => item.id)
  25. }
  26. .onReachEnd(() => {
  27. this.isListReachEnd = true;
  28. })
  29. .parallelGesture(
  30. PanGesture({ direction: PanDirection.Up, distance: 80 })
  31. .onActionStart(() => {
  32. if (this.isListReachEnd) {
  33. this.loadMoreArticles();
  34. this.isListReachEnd = false;
  35. }
  36. })
  37. )
  38. .padding(20)
  39. .scrollBar(BarState.Off)
  40. }
  41. .width('100%')
  42. .height('100%')
  43. .backgroundColor(0xF1F3F5)
  44. }
  45. }
  46. @Component
  47. struct ArticleCard {
  48. @Prop article: Article;
  49. build() {
  50. Row() {
  51. Image($r('app.media.icon'))
  52. .width(80)
  53. .height(80)
  54. .margin({ right: 20 })
  55. Column() {
  56. Text(this.article.title)
  57. .fontSize(20)
  58. .margin({ bottom: 8 })
  59. Text(this.article.brief)
  60. .fontSize(16)
  61. .fontColor(Color.Gray)
  62. .margin({ bottom: 8 })
  63. }
  64. .alignItems(HorizontalAlign.Start)
  65. .width('80%')
  66. .height('100%')
  67. }
  68. .padding(20)
  69. .borderRadius(12)
  70. .backgroundColor('#FFECECEC')
  71. .height(120)
  72. .width('100%')
  73. .justifyContent(FlexAlign.SpaceBetween)
  74. }
  75. }

当列表滚动到底部时,如果手势滑动距离超过指定的80,将触发loadMoreArticle()函数。此函数会在articleList数据源的尾部添加一个新的数据项,从而增加数据源的长度。

执行效果:
在这里插入图片描述

2.2.3 数据源数组项子属性变化
  1. @Entry
  2. @Component
  3. struct ArticleListView {
  4. @State articleList: Array<Article> = [
  5. new Article('001', '第0篇文章', '文章简介内容', false, 100),
  6. new Article('002', '第1篇文章', '文章简介内容', false, 100),
  7. new Article('003', '第2篇文章', '文章简介内容', false, 100),
  8. new Article('004', '第4篇文章', '文章简介内容', false, 100),
  9. new Article('005', '第5篇文章', '文章简介内容', false, 100),
  10. new Article('006', '第6篇文章', '文章简介内容', false, 100),
  11. ];
  12. build() {
  13. List() {
  14. ForEach(this.articleList, (item: Article) => {
  15. ListItem() {
  16. ArticleCard({
  17. article: item
  18. })
  19. .margin({ top: 20 })
  20. }
  21. }, (item: Article) => item.id)
  22. }
  23. .padding(20)
  24. .scrollBar(BarState.Off)
  25. .backgroundColor(0xF1F3F5)
  26. }
  27. }
  28. @Component
  29. struct ArticleCard {
  30. @ObjectLink article: Article;
  31. handleLiked() {
  32. this.article.isLiked = !this.article.isLiked;
  33. this.article.likesCount = this.article.isLiked ? this.article.likesCount + 1 : this.article.likesCount - 1;
  34. }
  35. build() {
  36. Row() {
  37. Image($r('app.media.icon'))
  38. .width(80)
  39. .height(80)
  40. .margin({ right: 20 })
  41. Column() {
  42. Text(this.article.title)
  43. .fontSize(20)
  44. .margin({ bottom: 8 })
  45. Text(this.article.brief)
  46. .fontSize(16)
  47. .fontColor(Color.Gray)
  48. .margin({ bottom: 8 })
  49. Row() {
  50. Image(this.article.isLiked ? $r('app.media.iconLiked') : $r('app.media.iconUnLiked'))
  51. .width(24)
  52. .height(24)
  53. .margin({ right: 8 })
  54. Text(this.article.likesCount.toString())
  55. .fontSize(16)
  56. }
  57. .onClick(() => this.handleLiked())
  58. .justifyContent(FlexAlign.Center)
  59. }
  60. .alignItems(HorizontalAlign.Start)
  61. .width('80%')
  62. .height('100%')
  63. }
  64. .padding(20)
  65. .borderRadius(12)
  66. .backgroundColor('#FFECECEC')
  67. .height(120)
  68. .width('100%')
  69. .justifyContent(FlexAlign.SpaceBetween)
  70. }
  71. }

执行结果:
在这里插入图片描述
== 注意:开发者在使用ForEach时应特别重视keyGenerator为键值生成函数,会根据键值生成函数确定替换的值。==

3.LazyForEach:数据懒加载

3.1 变化规则

LazyForEach是一种延迟执行的迭代方法,它可以帮助我们更高效地遍历和操作数组。与常规的ForEach方法不同,LazyForEach方法不会立即执行回调函数,而是在需要访问数组元素时才将回调函数应用于该元素。这种延迟执行的方式可以大大减少不必要的计算,提高代码性能。LazyForEach在处理大型数组或频繁进行迭代时特别有用。

LazyForEach接口描述:

  1. LazyForEach(
  2. dataSource: IDataSource, // 需要进行数据迭代的数据源
  3. itemGenerator: (item: any, index?: number) => void, // 子组件生成函数
  4. keyGenerator?: (item: any, index?: number) => string // 键值生成函数
  5. ): void

IDataSource接口描述:

  1. interface IDataSource {
  2. totalCount(): number; // 获得数据总数
  3. getData(index: number): Object; // 获取索引值对应的数据
  4. registerDataChangeListener(listener: DataChangeListener): void; // 注册数据改变的监听器
  5. unregisterDataChangeListener(listener: DataChangeListener): void; // 注销数据改变的监听器
  6. }

DataChangeListener接口描述:

  1. interface DataChangeListener {
  2. onDataReloaded(): void; // 重新加载数据时调用
  3. onDataAdded(index: number): void; // 添加数据时调用
  4. onDataMoved(from: number, to: number): void; // 数据移动起始位置与数据移动目标位置交换时调用
  5. onDataDeleted(index: number): void; // 删除数据时调用
  6. onDataChanged(index: number): void; // 改变数据时调用
  7. onDataAdd(index: number): void; // 添加数据时调用
  8. onDataMove(from: number, to: number): void; // 数据移动起始位置与数据移动目标位置交换时调用
  9. onDataDelete(index: number): void; // 删除数据时调用
  10. onDataChange(index: number): void; // 改变数据时调用
  11. }

3.2 使用场景

3.2.1 首次渲染
3.2.1.1 生成不同键值

1、正常渲染

  1. // Basic implementation of IDataSource to handle data listener
  2. class BasicDataSource implements IDataSource {
  3. private listeners: DataChangeListener[] = [];
  4. private originDataArray: string[] = [];
  5. public totalCount(): number {
  6. return 0;
  7. }
  8. public getData(index: number): string {
  9. return this.originDataArray[index];
  10. }
  11. // 该方法为框架侧调用,为LazyForEach组件向其数据源处添加listener监听
  12. registerDataChangeListener(listener: DataChangeListener): void {
  13. if (this.listeners.indexOf(listener) < 0) {
  14. console.info('add listener');
  15. this.listeners.push(listener);
  16. }
  17. }
  18. // 该方法为框架侧调用,为对应的LazyForEach组件在数据源处去除listener监听
  19. unregisterDataChangeListener(listener: DataChangeListener): void {
  20. const pos = this.listeners.indexOf(listener);
  21. if (pos >= 0) {
  22. console.info('remove listener');
  23. this.listeners.splice(pos, 1);
  24. }
  25. }
  26. // 通知LazyForEach组件需要重载所有子组件
  27. notifyDataReload(): void {
  28. this.listeners.forEach(listener => {
  29. listener.onDataReloaded();
  30. })
  31. }
  32. // 通知LazyForEach组件需要在index对应索引处添加子组件
  33. notifyDataAdd(index: number): void {
  34. this.listeners.forEach(listener => {
  35. listener.onDataAdd(index);
  36. })
  37. }
  38. // 通知LazyForEach组件在index对应索引处数据有变化,需要重建该子组件
  39. notifyDataChange(index: number): void {
  40. this.listeners.forEach(listener => {
  41. listener.onDataChange(index);
  42. })
  43. }
  44. // 通知LazyForEach组件需要在index对应索引处删除该子组件
  45. notifyDataDelete(index: number): void {
  46. this.listeners.forEach(listener => {
  47. listener.onDataDelete(index);
  48. })
  49. }
  50. }
  51. class MyDataSource extends BasicDataSource {
  52. private dataArray: string[] = [];
  53. public totalCount(): number {
  54. return this.dataArray.length;
  55. }
  56. public getData(index: number): string {
  57. return this.dataArray[index];
  58. }
  59. public addData(index: number, data: string): void {
  60. this.dataArray.splice(index, 0, data);
  61. this.notifyDataAdd(index);
  62. }
  63. public pushData(data: string): void {
  64. this.dataArray.push(data);
  65. this.notifyDataAdd(this.dataArray.length - 1);
  66. }
  67. }
  68. @Entry
  69. @Component
  70. struct MyComponent {
  71. private data: MyDataSource = new MyDataSource();
  72. aboutToAppear() {
  73. for (let i = 0; i <= 20; i++) {
  74. this.data.pushData(`Hello ${i}`)
  75. }
  76. }
  77. build() {
  78. List({ space: 3 }) {
  79. LazyForEach(this.data, (item: string) => {
  80. ListItem() {
  81. Row() {
  82. Text(item).fontSize(50)
  83. .onAppear(() => {
  84. console.info("appear:" + item)
  85. })
  86. }.margin({ left: 10, right: 10 })
  87. }
  88. }, (item: string) => item)
  89. }.cachedCount(5)
  90. }
  91. }

2、键值相同时错误渲染

  1. class BasicDataSource implements IDataSource {
  2. private listeners: DataChangeListener[] = [];
  3. private originDataArray: string[] = [];
  4. public totalCount(): number {
  5. return 0;
  6. }
  7. public getData(index: number): string {
  8. return this.originDataArray[index];
  9. }
  10. registerDataChangeListener(listener: DataChangeListener): void {
  11. if (this.listeners.indexOf(listener) < 0) {
  12. console.info('add listener');
  13. this.listeners.push(listener);
  14. }
  15. }
  16. unregisterDataChangeListener(listener: DataChangeListener): void {
  17. const pos = this.listeners.indexOf(listener);
  18. if (pos >= 0) {
  19. console.info('remove listener');
  20. this.listeners.splice(pos, 1);
  21. }
  22. }
  23. notifyDataReload(): void {
  24. this.listeners.forEach(listener => {
  25. listener.onDataReloaded();
  26. })
  27. }
  28. notifyDataAdd(index: number): void {
  29. this.listeners.forEach(listener => {
  30. listener.onDataAdd(index);
  31. })
  32. }
  33. notifyDataChange(index: number): void {
  34. this.listeners.forEach(listener => {
  35. listener.onDataChange(index);
  36. })
  37. }
  38. notifyDataDelete(index: number): void {
  39. this.listeners.forEach(listener => {
  40. listener.onDataDelete(index);
  41. })
  42. }
  43. }
  44. class MyDataSource extends BasicDataSource {
  45. private dataArray: string[] = [];
  46. public totalCount(): number {
  47. return this.dataArray.length;
  48. }
  49. public getData(index: number): string {
  50. return this.dataArray[index];
  51. }
  52. public addData(index: number, data: string): void {
  53. this.dataArray.splice(index, 0, data);
  54. this.notifyDataAdd(index);
  55. }
  56. public pushData(data: string): void {
  57. this.dataArray.push(data);
  58. this.notifyDataAdd(this.dataArray.length - 1);
  59. }
  60. }
  61. @Entry
  62. @Component
  63. struct MyComponent {
  64. private data: MyDataSource = new MyDataSource();
  65. aboutToAppear() {
  66. for (let i = 0; i <= 20; i++) {
  67. this.data.pushData(`Hello ${i}`)
  68. }
  69. }
  70. build() {
  71. List({ space: 3 }) {
  72. LazyForEach(this.data, (item: string) => {
  73. ListItem() {
  74. Row() {
  75. Text(item).fontSize(50)
  76. .onAppear(() => {
  77. console.info("appear:" + item)
  78. })
  79. }.margin({ left: 10, right: 10 })
  80. }
  81. }, (item: string) => 'same key')
  82. }.cachedCount(5)
  83. }
  84. }
3.2.2 非首次渲染
3.2.2.1 添加数据
  1. class BasicDataSource implements IDataSource {
  2. private listeners: DataChangeListener[] = [];
  3. private originDataArray: string[] = [];
  4. public totalCount(): number {
  5. return 0;
  6. }
  7. public getData(index: number): string {
  8. return this.originDataArray[index];
  9. }
  10. registerDataChangeListener(listener: DataChangeListener): void {
  11. if (this.listeners.indexOf(listener) < 0) {
  12. console.info('add listener');
  13. this.listeners.push(listener);
  14. }
  15. }
  16. unregisterDataChangeListener(listener: DataChangeListener): void {
  17. const pos = this.listeners.indexOf(listener);
  18. if (pos >= 0) {
  19. console.info('remove listener');
  20. this.listeners.splice(pos, 1);
  21. }
  22. }
  23. notifyDataReload(): void {
  24. this.listeners.forEach(listener => {
  25. listener.onDataReloaded();
  26. })
  27. }
  28. notifyDataAdd(index: number): void {
  29. this.listeners.forEach(listener => {
  30. listener.onDataAdd(index);
  31. })
  32. }
  33. notifyDataChange(index: number): void {
  34. this.listeners.forEach(listener => {
  35. listener.onDataChange(index);
  36. })
  37. }
  38. notifyDataDelete(index: number): void {
  39. this.listeners.forEach(listener => {
  40. listener.onDataDelete(index);
  41. })
  42. }
  43. }
  44. class MyDataSource extends BasicDataSource {
  45. private dataArray: string[] = [];
  46. public totalCount(): number {
  47. return this.dataArray.length;
  48. }
  49. public getData(index: number): string {
  50. return this.dataArray[index];
  51. }
  52. public addData(index: number, data: string): void {
  53. this.dataArray.splice(index, 0, data);
  54. this.notifyDataAdd(index);
  55. }
  56. public pushData(data: string): void {
  57. this.dataArray.push(data);
  58. this.notifyDataAdd(this.dataArray.length - 1);
  59. }
  60. }
  61. @Entry
  62. @Component
  63. struct MyComponent {
  64. private data: MyDataSource = new MyDataSource();
  65. aboutToAppear() {
  66. for (let i = 0; i <= 20; i++) {
  67. this.data.pushData(`Hello ${i}`)
  68. }
  69. }
  70. build() {
  71. List({ space: 3 }) {
  72. LazyForEach(this.data, (item: string) => {
  73. ListItem() {
  74. Row() {
  75. Text(item).fontSize(50)
  76. .onAppear(() => {
  77. console.info("appear:" + item)
  78. })
  79. }.margin({ left: 10, right: 10 })
  80. }
  81. .onClick(() => {
  82. // 点击追加子组件
  83. this.data.pushData(`Hello ${this.data.totalCount()}`);
  84. })
  85. }, (item: string) => item)
  86. }.cachedCount(5)
  87. }
  88. }
3.2.2.2 删除数据
  1. class BasicDataSource implements IDataSource {
  2. private listeners: DataChangeListener[] = [];
  3. private originDataArray: string[] = [];
  4. public totalCount(): number {
  5. return 0;
  6. }
  7. public getData(index: number): string {
  8. return this.originDataArray[index];
  9. }
  10. registerDataChangeListener(listener: DataChangeListener): void {
  11. if (this.listeners.indexOf(listener) < 0) {
  12. console.info('add listener');
  13. this.listeners.push(listener);
  14. }
  15. }
  16. unregisterDataChangeListener(listener: DataChangeListener): void {
  17. const pos = this.listeners.indexOf(listener);
  18. if (pos >= 0) {
  19. console.info('remove listener');
  20. this.listeners.splice(pos, 1);
  21. }
  22. }
  23. notifyDataReload(): void {
  24. this.listeners.forEach(listener => {
  25. listener.onDataReloaded();
  26. })
  27. }
  28. notifyDataAdd(index: number): void {
  29. this.listeners.forEach(listener => {
  30. listener.onDataAdd(index);
  31. })
  32. }
  33. notifyDataChange(index: number): void {
  34. this.listeners.forEach(listener => {
  35. listener.onDataChange(index);
  36. })
  37. }
  38. notifyDataDelete(index: number): void {
  39. this.listeners.forEach(listener => {
  40. listener.onDataDelete(index);
  41. })
  42. }
  43. }
  44. class MyDataSource extends BasicDataSource {
  45. dataArray: string[] = [];
  46. public totalCount(): number {
  47. return this.dataArray.length;
  48. }
  49. public getData(index: number): string {
  50. return this.dataArray[index];
  51. }
  52. public addData(index: number, data: string): void {
  53. this.dataArray.splice(index, 0, data);
  54. this.notifyDataAdd(index);
  55. }
  56. public pushData(data: string): void {
  57. this.dataArray.push(data);
  58. this.notifyDataAdd(this.dataArray.length - 1);
  59. }
  60. public deleteData(index: number): void {
  61. this.dataArray.splice(index, 1);
  62. this.notifyDataDelete(index);
  63. }
  64. }
  65. @Entry
  66. @Component
  67. struct MyComponent {
  68. private data: MyDataSource = new MyDataSource();
  69. aboutToAppear() {
  70. for (let i = 0; i <= 20; i++) {
  71. this.data.pushData(`Hello ${i}`)
  72. }
  73. }
  74. build() {
  75. List({ space: 3 }) {
  76. LazyForEach(this.data, (item: string, index: number) => {
  77. ListItem() {
  78. Row() {
  79. Text(item).fontSize(50)
  80. .onAppear(() => {
  81. console.info("appear:" + item)
  82. })
  83. }.margin({ left: 10, right: 10 })
  84. }
  85. .onClick(() => {
  86. // 点击删除子组件
  87. this.data.deleteData(this.data.dataArray.indexOf(item));
  88. })
  89. }, (item: string) => item)
  90. }.cachedCount(5)
  91. }
  92. }
3.2.2.3 改变单个数据
  1. class BasicDataSource implements IDataSource {
  2. private listeners: DataChangeListener[] = [];
  3. private originDataArray: string[] = [];
  4. public totalCount(): number {
  5. return 0;
  6. }
  7. public getData(index: number): string {
  8. return this.originDataArray[index];
  9. }
  10. registerDataChangeListener(listener: DataChangeListener): void {
  11. if (this.listeners.indexOf(listener) < 0) {
  12. console.info('add listener');
  13. this.listeners.push(listener);
  14. }
  15. }
  16. unregisterDataChangeListener(listener: DataChangeListener): void {
  17. const pos = this.listeners.indexOf(listener);
  18. if (pos >= 0) {
  19. console.info('remove listener');
  20. this.listeners.splice(pos, 1);
  21. }
  22. }
  23. notifyDataReload(): void {
  24. this.listeners.forEach(listener => {
  25. listener.onDataReloaded();
  26. })
  27. }
  28. notifyDataAdd(index: number): void {
  29. this.listeners.forEach(listener => {
  30. listener.onDataAdd(index);
  31. })
  32. }
  33. notifyDataChange(index: number): void {
  34. this.listeners.forEach(listener => {
  35. listener.onDataChange(index);
  36. })
  37. }
  38. notifyDataDelete(index: number): void {
  39. this.listeners.forEach(listener => {
  40. listener.onDataDelete(index);
  41. })
  42. }
  43. }
  44. class MyDataSource extends BasicDataSource {
  45. private dataArray: string[] = [];
  46. public totalCount(): number {
  47. return this.dataArray.length;
  48. }
  49. public getData(index: number): string {
  50. return this.dataArray[index];
  51. }
  52. public addData(index: number, data: string): void {
  53. this.dataArray.splice(index, 0, data);
  54. this.notifyDataAdd(index);
  55. }
  56. public pushData(data: string): void {
  57. this.dataArray.push(data);
  58. this.notifyDataAdd(this.dataArray.length - 1);
  59. }
  60. public deleteData(index: number): void {
  61. this.dataArray.splice(index, 1);
  62. this.notifyDataDelete(index);
  63. }
  64. public changeData(index: number, data: string): void {
  65. this.dataArray.splice(index, 0, data);
  66. this.notifyDataChange(index);
  67. }
  68. }
  69. @Entry
  70. @Component
  71. struct MyComponent {
  72. private moved: number[] = [];
  73. private data: MyDataSource = new MyDataSource();
  74. aboutToAppear() {
  75. for (let i = 0; i <= 20; i++) {
  76. this.data.pushData(`Hello ${i}`)
  77. }
  78. }
  79. build() {
  80. List({ space: 3 }) {
  81. LazyForEach(this.data, (item: string, index: number) => {
  82. ListItem() {
  83. Row() {
  84. Text(item).fontSize(50)
  85. .onAppear(() => {
  86. console.info("appear:" + item)
  87. })
  88. }.margin({ left: 10, right: 10 })
  89. }
  90. .onClick(() => {
  91. this.data.changeData(index, item + '00');
  92. })
  93. }, (item: string) => item)
  94. }.cachedCount(5)
  95. }
  96. }
3.2.2.4 改变多个数据
  1. class BasicDataSource implements IDataSource {
  2. private listeners: DataChangeListener[] = [];
  3. private originDataArray: string[] = [];
  4. public totalCount(): number {
  5. return 0;
  6. }
  7. public getData(index: number): string {
  8. return this.originDataArray[index];
  9. }
  10. registerDataChangeListener(listener: DataChangeListener): void {
  11. if (this.listeners.indexOf(listener) < 0) {
  12. console.info('add listener');
  13. this.listeners.push(listener);
  14. }
  15. }
  16. unregisterDataChangeListener(listener: DataChangeListener): void {
  17. const pos = this.listeners.indexOf(listener);
  18. if (pos >= 0) {
  19. console.info('remove listener');
  20. this.listeners.splice(pos, 1);
  21. }
  22. }
  23. notifyDataReload(): void {
  24. this.listeners.forEach(listener => {
  25. listener.onDataReloaded();
  26. })
  27. }
  28. notifyDataAdd(index: number): void {
  29. this.listeners.forEach(listener => {
  30. listener.onDataAdd(index);
  31. })
  32. }
  33. notifyDataChange(index: number): void {
  34. this.listeners.forEach(listener => {
  35. listener.onDataChange(index);
  36. })
  37. }
  38. notifyDataDelete(index: number): void {
  39. this.listeners.forEach(listener => {
  40. listener.onDataDelete(index);
  41. })
  42. }
  43. }
  44. class MyDataSource extends BasicDataSource {
  45. private dataArray: string[] = [];
  46. public totalCount(): number {
  47. return this.dataArray.length;
  48. }
  49. public getData(index: number): string {
  50. return this.dataArray[index];
  51. }
  52. public addData(index: number, data: string): void {
  53. this.dataArray.splice(index, 0, data);
  54. this.notifyDataAdd(index);
  55. }
  56. public pushData(data: string): void {
  57. this.dataArray.push(data);
  58. this.notifyDataAdd(this.dataArray.length - 1);
  59. }
  60. public deleteData(index: number): void {
  61. this.dataArray.splice(index, 1);
  62. this.notifyDataDelete(index);
  63. }
  64. public changeData(index: number): void {
  65. this.notifyDataChange(index);
  66. }
  67. public reloadData(): void {
  68. this.notifyDataReload();
  69. }
  70. public modifyAllData(): void {
  71. this.dataArray = this.dataArray.map((item: string) => {
  72. return item + '0';
  73. })
  74. }
  75. }
  76. @Entry
  77. @Component
  78. struct MyComponent {
  79. private moved: number[] = [];
  80. private data: MyDataSource = new MyDataSource();
  81. aboutToAppear() {
  82. for (let i = 0; i <= 20; i++) {
  83. this.data.pushData(`Hello ${i}`)
  84. }
  85. }
  86. build() {
  87. List({ space: 3 }) {
  88. LazyForEach(this.data, (item: string, index: number) => {
  89. ListItem() {
  90. Row() {
  91. Text(item).fontSize(50)
  92. .onAppear(() => {
  93. console.info("appear:" + item)
  94. })
  95. }.margin({ left: 10, right: 10 })
  96. }
  97. .onClick(() => {
  98. this.data.modifyAllData();
  99. this.data.reloadData();
  100. })
  101. }, (item: string) => item)
  102. }.cachedCount(5)
  103. }
  104. }
3.2.2.5 改变数据子属性
  1. class BasicDataSource implements IDataSource {
  2. private listeners: DataChangeListener[] = [];
  3. private originDataArray: StringData[] = [];
  4. public totalCount(): number {
  5. return 0;
  6. }
  7. public getData(index: number): StringData {
  8. return this.originDataArray[index];
  9. }
  10. registerDataChangeListener(listener: DataChangeListener): void {
  11. if (this.listeners.indexOf(listener) < 0) {
  12. console.info('add listener');
  13. this.listeners.push(listener);
  14. }
  15. }
  16. unregisterDataChangeListener(listener: DataChangeListener): void {
  17. const pos = this.listeners.indexOf(listener);
  18. if (pos >= 0) {
  19. console.info('remove listener');
  20. this.listeners.splice(pos, 1);
  21. }
  22. }
  23. notifyDataReload(): void {
  24. this.listeners.forEach(listener => {
  25. listener.onDataReloaded();
  26. })
  27. }
  28. notifyDataAdd(index: number): void {
  29. this.listeners.forEach(listener => {
  30. listener.onDataAdd(index);
  31. })
  32. }
  33. notifyDataChange(index: number): void {
  34. this.listeners.forEach(listener => {
  35. listener.onDataChange(index);
  36. })
  37. }
  38. notifyDataDelete(index: number): void {
  39. this.listeners.forEach(listener => {
  40. listener.onDataDelete(index);
  41. })
  42. }
  43. }
  44. class MyDataSource extends BasicDataSource {
  45. private dataArray: StringData[] = [];
  46. public totalCount(): number {
  47. return this.dataArray.length;
  48. }
  49. public getData(index: number): StringData {
  50. return this.dataArray[index];
  51. }
  52. public addData(index: number, data: StringData): void {
  53. this.dataArray.splice(index, 0, data);
  54. this.notifyDataAdd(index);
  55. }
  56. public pushData(data: StringData): void {
  57. this.dataArray.push(data);
  58. this.notifyDataAdd(this.dataArray.length - 1);
  59. }
  60. }
  61. @Observed
  62. class StringData {
  63. message: string;
  64. constructor(message: string) {
  65. this.message = message;
  66. }
  67. }
  68. @Entry
  69. @Component
  70. struct MyComponent {
  71. private moved: number[] = [];
  72. @State data: MyDataSource = new MyDataSource();
  73. aboutToAppear() {
  74. for (let i = 0; i <= 20; i++) {
  75. this.data.pushData(new StringData(`Hello ${i}`));
  76. }
  77. }
  78. build() {
  79. List({ space: 3 }) {
  80. LazyForEach(this.data, (item: StringData, index: number) => {
  81. ListItem() {
  82. ChildComponent({data: item})
  83. }
  84. .onClick(() => {
  85. item.message += '0';
  86. })
  87. }, (item: StringData, index: number) => index.toString())
  88. }.cachedCount(5)
  89. }
  90. }
  91. @Component
  92. struct ChildComponent {
  93. @ObjectLink data: StringData
  94. build() {
  95. Row() {
  96. Text(this.data.message).fontSize(50)
  97. .onAppear(() => {
  98. console.info("appear:" + this.data.message)
  99. })
  100. }.margin({ left: 10, right: 10 })
  101. }
  102. }
3.2.3 问题点
3.2.3.1 索引重置
  1. class BasicDataSource implements IDataSource {
  2. private listeners: DataChangeListener[] = [];
  3. private originDataArray: string[] = [];
  4. public totalCount(): number {
  5. return 0;
  6. }
  7. public getData(index: number): string {
  8. return this.originDataArray[index];
  9. }
  10. registerDataChangeListener(listener: DataChangeListener): void {
  11. if (this.listeners.indexOf(listener) < 0) {
  12. console.info('add listener');
  13. this.listeners.push(listener);
  14. }
  15. }
  16. unregisterDataChangeListener(listener: DataChangeListener): void {
  17. const pos = this.listeners.indexOf(listener);
  18. if (pos >= 0) {
  19. console.info('remove listener');
  20. this.listeners.splice(pos, 1);
  21. }
  22. }
  23. notifyDataReload(): void {
  24. this.listeners.forEach(listener => {
  25. listener.onDataReloaded();
  26. })
  27. }
  28. notifyDataAdd(index: number): void {
  29. this.listeners.forEach(listener => {
  30. listener.onDataAdd(index);
  31. })
  32. }
  33. notifyDataChange(index: number): void {
  34. this.listeners.forEach(listener => {
  35. listener.onDataChange(index);
  36. })
  37. }
  38. notifyDataDelete(index: number): void {
  39. this.listeners.forEach(listener => {
  40. listener.onDataDelete(index);
  41. })
  42. }
  43. }
  44. class MyDataSource extends BasicDataSource {
  45. private dataArray: string[] = [];
  46. public totalCount(): number {
  47. return this.dataArray.length;
  48. }
  49. public getData(index: number): string {
  50. return this.dataArray[index];
  51. }
  52. public addData(index: number, data: string): void {
  53. this.dataArray.splice(index, 0, data);
  54. this.notifyDataAdd(index);
  55. }
  56. public pushData(data: string): void {
  57. this.dataArray.push(data);
  58. this.notifyDataAdd(this.dataArray.length - 1);
  59. }
  60. public deleteData(index: number): void {
  61. this.dataArray.splice(index, 1);
  62. this.notifyDataDelete(index);
  63. }
  64. public reloadData(): void {
  65. this.notifyDataReload();
  66. }
  67. }
  68. @Entry
  69. @Component
  70. struct MyComponent {
  71. private data: MyDataSource = new MyDataSource();
  72. aboutToAppear() {
  73. for (let i = 0; i <= 20; i++) {
  74. this.data.pushData(`Hello ${i}`)
  75. }
  76. }
  77. build() {
  78. List({ space: 3 }) {
  79. LazyForEach(this.data, (item: string, index: number) => {
  80. ListItem() {
  81. Row() {
  82. Text(item).fontSize(50)
  83. .onAppear(() => {
  84. console.info("appear:" + item)
  85. })
  86. }.margin({ left: 10, right: 10 })
  87. }
  88. .onClick(() => {
  89. // 点击删除子组件
  90. this.data.deleteData(index);
  91. // 重置所有子组件的index索引
  92. this.data.reloadData();
  93. })
  94. }, (item: string, index: number) => item + index.toString())
  95. }.cachedCount(5)
  96. }
  97. }
3.2.3.2 图片闪烁
  1. class BasicDataSource implements IDataSource {
  2. private listeners: DataChangeListener[] = [];
  3. private originDataArray: StringData[] = [];
  4. public totalCount(): number {
  5. return 0;
  6. }
  7. public getData(index: number): StringData {
  8. return this.originDataArray[index];
  9. }
  10. registerDataChangeListener(listener: DataChangeListener): void {
  11. if (this.listeners.indexOf(listener) < 0) {
  12. console.info('add listener');
  13. this.listeners.push(listener);
  14. }
  15. }
  16. unregisterDataChangeListener(listener: DataChangeListener): void {
  17. const pos = this.listeners.indexOf(listener);
  18. if (pos >= 0) {
  19. console.info('remove listener');
  20. this.listeners.splice(pos, 1);
  21. }
  22. }
  23. notifyDataReload(): void {
  24. this.listeners.forEach(listener => {
  25. listener.onDataReloaded();
  26. })
  27. }
  28. notifyDataAdd(index: number): void {
  29. this.listeners.forEach(listener => {
  30. listener.onDataAdd(index);
  31. })
  32. }
  33. notifyDataChange(index: number): void {
  34. this.listeners.forEach(listener => {
  35. listener.onDataChange(index);
  36. })
  37. }
  38. notifyDataDelete(index: number): void {
  39. this.listeners.forEach(listener => {
  40. listener.onDataDelete(index);
  41. })
  42. }
  43. }
  44. class MyDataSource extends BasicDataSource {
  45. private dataArray: StringData[] = [];
  46. public totalCount(): number {
  47. return this.dataArray.length;
  48. }
  49. public getData(index: number): StringData {
  50. return this.dataArray[index];
  51. }
  52. public addData(index: number, data: StringData): void {
  53. this.dataArray.splice(index, 0, data);
  54. this.notifyDataAdd(index);
  55. }
  56. public pushData(data: StringData): void {
  57. this.dataArray.push(data);
  58. this.notifyDataAdd(this.dataArray.length - 1);
  59. }
  60. }
  61. @Observed
  62. class StringData {
  63. message: string;
  64. imgSrc: Resource;
  65. constructor(message: string, imgSrc: Resource) {
  66. this.message = message;
  67. this.imgSrc = imgSrc;
  68. }
  69. }
  70. @Entry
  71. @Component
  72. struct MyComponent {
  73. @State data: MyDataSource = new MyDataSource();
  74. aboutToAppear() {
  75. for (let i = 0; i <= 20; i++) {
  76. this.data.pushData(new StringData(`Hello ${i}`, $r('app.media.img')));
  77. }
  78. }
  79. build() {
  80. List({ space: 3 }) {
  81. LazyForEach(this.data, (item: StringData, index: number) => {
  82. ListItem() {
  83. ChildComponent({data: item})
  84. }
  85. .onClick(() => {
  86. item.message += '0';
  87. })
  88. }, (item: StringData, index: number) => index.toString())
  89. }.cachedCount(5)
  90. }
  91. }
  92. @Component
  93. struct ChildComponent {
  94. @ObjectLink data: StringData
  95. build() {
  96. Column() {
  97. Text(this.data.message).fontSize(50)
  98. .onAppear(() => {
  99. console.info("appear:" + this.data.message)
  100. })
  101. Image(this.data.imgSrc)
  102. .width(500)
  103. .height(200)
  104. }.margin({ left: 10, right: 10 })
  105. }
  106. }
3.2.3.3 ObjectLink属性变化后UI更新
  1. class BasicDataSource implements IDataSource {
  2. private listeners: DataChangeListener[] = [];
  3. private originDataArray: StringData[] = [];
  4. public totalCount(): number {
  5. return 0;
  6. }
  7. public getData(index: number): StringData {
  8. return this.originDataArray[index];
  9. }
  10. registerDataChangeListener(listener: DataChangeListener): void {
  11. if (this.listeners.indexOf(listener) < 0) {
  12. console.info('add listener');
  13. this.listeners.push(listener);
  14. }
  15. }
  16. unregisterDataChangeListener(listener: DataChangeListener): void {
  17. const pos = this.listeners.indexOf(listener);
  18. if (pos >= 0) {
  19. console.info('remove listener');
  20. this.listeners.splice(pos, 1);
  21. }
  22. }
  23. notifyDataReload(): void {
  24. this.listeners.forEach(listener => {
  25. listener.onDataReloaded();
  26. })
  27. }
  28. notifyDataAdd(index: number): void {
  29. this.listeners.forEach(listener => {
  30. listener.onDataAdd(index);
  31. })
  32. }
  33. notifyDataChange(index: number): void {
  34. this.listeners.forEach(listener => {
  35. listener.onDataChange(index);
  36. })
  37. }
  38. notifyDataDelete(index: number): void {
  39. this.listeners.forEach(listener => {
  40. listener.onDataDelete(index);
  41. })
  42. }
  43. }
  44. class MyDataSource extends BasicDataSource {
  45. private dataArray: StringData[] = [];
  46. public totalCount(): number {
  47. return this.dataArray.length;
  48. }
  49. public getData(index: number): StringData {
  50. return this.dataArray[index];
  51. }
  52. public addData(index: number, data: StringData): void {
  53. this.dataArray.splice(index, 0, data);
  54. this.notifyDataAdd(index);
  55. }
  56. public pushData(data: StringData): void {
  57. this.dataArray.push(data);
  58. this.notifyDataAdd(this.dataArray.length - 1);
  59. }
  60. }
  61. @Observed
  62. class StringData {
  63. message: NestedString;
  64. constructor(message: NestedString) {
  65. this.message = message;
  66. }
  67. }
  68. @Observed
  69. class NestedString {
  70. message: string;
  71. constructor(message: string) {
  72. this.message = message;
  73. }
  74. }
  75. @Entry
  76. @Component
  77. struct MyComponent {
  78. private moved: number[] = [];
  79. @State data: MyDataSource = new MyDataSource();
  80. aboutToAppear() {
  81. for (let i = 0; i <= 20; i++) {
  82. this.data.pushData(new StringData(new NestedString(`Hello ${i}`)));
  83. }
  84. }
  85. build() {
  86. List({ space: 3 }) {
  87. LazyForEach(this.data, (item: StringData, index: number) => {
  88. ListItem() {
  89. ChildComponent({data: item})
  90. }
  91. .onClick(() => {
  92. item.message = new NestedString(item.message.message + '0');
  93. })
  94. }, (item: StringData, index: number) => item.toString() + index.toString())
  95. }.cachedCount(5)
  96. }
  97. }
  98. @Component
  99. struct ChildComponent {
  100. @ObjectLink data: StringData
  101. build() {
  102. Row() {
  103. Text(this.data.message.message).fontSize(50)
  104. .onAppear(() => {
  105. console.info("appear:" + this.data.message.message)
  106. })
  107. }.margin({ left: 10, right: 10 })
  108. }
  109. }

 声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】

推荐阅读
相关标签