ts-rending-control-syntax-foreach.md 5.2 KB
Newer Older
Z
zengyawen 已提交
1
# 循环渲染
Z
zengyawen 已提交
2

L
luoying_ace_admin 已提交
3
开发框架提供循环渲染(ForEach组件)来迭代数组,并为每个数组项创建相应的组件。当循环渲染的元素较多时,会出现页面加载变慢的情况,出于性能考虑,建议使用[LazyForEach](ts-rending-control-syntax-lazyforeach.md)代替。ForEach定义如下:
Z
zengyawen 已提交
4

Z
zengyawen 已提交
5

H
HelloCrease 已提交
6
```ts
Z
zengyawen 已提交
7 8
ForEach(
    arr: any[], // Array to be iterated
Z
zengyawen 已提交
9 10
    itemGenerator: (item: any, index?: number) => void, // child component generator
    keyGenerator?: (item: any, index?: number) => string // (optional) Unique key generator, which is recommended.
Z
zengyawen 已提交
11 12 13
)
```

Z
zengyawen 已提交
14 15 16 17 18 19 20

## ForEach


ForEach(arr: any[],itemGenerator: (item: any, index?: number) => void, keyGenerator?: (item: any, index?: number) => string):void


21
表1 参数说明
Z
zengyawen 已提交
22

H
HelloCrease 已提交
23 24 25 26 27
| 参数名           | 参数类型                                     | 必填   | 默认值  | 参数描述                                     |
| ------------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| arr           | any[]                                    | 是    | -    | 必须是数组,允许空数组,空数组场景下不会创建子组件。同时允许设置返回值为数组类型的函数,例如arr.slice(1, 3),设置的函数不得改变包括数组本身在内的任何状态变量,如Array.splice、Array.sort或Array.reverse这些改变原数组的函数。 |
| itemGenerator | (item: any, index?: number) => void | 是    | -    | 生成子组件的lambda函数,为给定数组项生成一个或多个子组件,单个组件和子组件列表必须括在大括号“{....}”中。 |
| keyGenerator  | (item: any, index?: number) => string | 否    | -    | 匿名参数,用于给定数组项生成唯一且稳定的键值。当子项在数组中的位置更改时,子项的键值不得更改,当数组中的子项被新项替换时,被替换项的键值和新项的键值必须不同。键值生成器的功能是可选的,但是,为了使开发框架能够更好地识别数组更改,提高性能,建议提供。如将数组反向时,如果没有提供键值生成器,则ForEach中的所有节点都将重建。 |
Z
zengyawen 已提交
28 29


H
HelloCrease 已提交
30
> **说明:**
Z
zengyawen 已提交
31
> - 必须在容器组件内使用;
H
HelloCrease 已提交
32
>
33
> - 生成的子组件允许在ForEach的父容器组件中,允许子组件生成器函数中包含if/else条件渲染,同时也允许ForEach包含在if/else条件渲染语句中;
H
HelloCrease 已提交
34
>
Z
zengyawen 已提交
35
> - 子项生成器函数的调用顺序不一定和数组中的数据项相同,在开发过程中不要假设子项生成器和键值生成器函数是否执行以及执行顺序。如下示例可能无法正常工作:
H
HelloCrease 已提交
36
>   ```ts
Z
zengyawen 已提交
37 38
>   ForEach(anArray, item => {Text(`${++counter}. item.label`)})
>   ```
H
HelloCrease 已提交
39
>
Z
zengyawen 已提交
40
>   正确的示例如下:
H
HelloCrease 已提交
41 42
>
>   ```ts
Z
zengyawen 已提交
43 44 45 46 47 48 49
>   ForEach(anArray.map((item1, index1) => { return { i: index1 + 1, data: item1 }; }), 
>           item => Text(`${item.i}. item.data.label`),
>           item => item.data.id.toString())
>   ```


## 示例
Z
zengyawen 已提交
50 51 52

简单类型数组示例:

H
HelloCrease 已提交
53 54
```ts
// xxx.ets
Z
zengyawen 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
@Entry
@Component
struct MyComponent {
    @State arr: number[] = [10, 20, 30]
    build() {
        Column() {
            Button() {
                Text('Reverse Array')
            }.onClick(() => {
                this.arr.reverse()
            })

            ForEach(this.arr,                         // Parameter 1: array to be iterated
                    (item: number) => {               // Parameter 2: item generator
                        Text(`item value: ${item}`)
                        Divider()
                    },
                    (item: number) => item.toString() // Parameter 3: unique key generator, which is optional but recommended.
            )
        }
    }
}
```

复杂类型数组示例:
H
HelloCrease 已提交
80 81
```ts
// xxx.ets
Z
zengyawen 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
class Month {
  year: number
  month: number
  days: Array<number>

  constructor(year, month, days) {
    this.year = year;
    this.month = month;
    this.days = days;
  }
}

@Entry
@Component
struct Calendar1 {
// simulate with 6 months
  @State calendar: Month[] = [
    new Month(2020, 1, [...Array(31).keys()]),
    new Month(2020, 2, [...Array(28).keys()]),
    new Month(2020, 3, [...Array(31).keys()]),
    new Month(2020, 4, [...Array(30).keys()]),
    new Month(2020, 5, [...Array(31).keys()]),
    new Month(2020, 6, [...Array(30).keys()]),
  ]

  build() {
    Column() {
      Button('next month')
        .onClick(() => {
          this.calendar.shift()
          this.calendar.push({
            year: 2020,
            month: 7,
            days: [...Array(31)
              .keys()]
          })
        })
      ForEach(this.calendar,
        (item: Month) => {
          Text('month:' + item.month)
            .fontSize(30)
            .padding(20)
          Grid() {
            ForEach(item.days,
              (day: number) => {
                GridItem() {
                  Text((day + 1).toString())
                    .fontSize(30)
                }
              },
              (day: number) => day.toString())
          }
          .columnsTemplate('1fr 1fr 1fr 1fr 1fr 1fr 1fr')
          .rowsGap(20)
        },
        // field is used together with year and month as the unique ID of the month.
        (item: Month) => (item.year * 12 + item.month).toString())
    }
  }
}
```