1/* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16/* 17 StateArrayReverse test case 18 19 The purpose of this test case is verify what happens when re-ordering the Widgets / Components 20 of same type. Here, the test is done with built-in text (not with a own subclass of JSView) 21 22 The expectation is that TextElement objects are created only once, then put to new order. 23 For this to work, each time a TextComponent is created it needs to be assigned the same unique key. 24 25 This is why anArray is not a simple array of strings. strings are not uniquely identifyable 26 (in SwiftUI). Therefore, the app needs to provide a unique id for each array item. 27 We do so by making each array item an object with a unique id. 28 29 this id should be used as the 'key' argument when creating a Text. 30 31*/ 32 33class Item1 { 34 id:number; 35 label:string; 36 37 constructor(id:number, label:string){ 38 this.id = id; 39 this.label = label; 40 } 41} 42 43@Entry 44@Component 45struct ShufflingArrayContainer1 { 46 47 @State anArray:Item1[] = [ 48 new Item1(1, "Text 1"), 49 new Item1(2, "Text 2"), 50 new Item1(3, "Text 3"), 51 new Item1(4, "Text 4"), 52 new Item1(5, "Text 5") 53 ]; 54 55 build() { 56 Column(){ 57 ForEach(this.anArray, 58 (item:Item1) => {Text(item.label)}, 59 (item:Item1) => item.id.toString() 60 ) //ForEach 61 Button("Reverse array") 62 .width(500.0) 63 .height(150.0) 64 .onClick(() => { 65 this.anArray.reverse(); 66 console.log("onClick handler on ShufflingArrayContainer1, this.anArray: " + JSON.stringify(this.anArray)); 67 }) //Button 68 } // Column 69 } // build 70} // class 71