1/* 2 * Copyright (c) 2023 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 16import Constants from '../../util/Constants'; 17 18@Preview 19@Component 20export struct BetterUseIf { 21 @State isVisible: boolean = false; // 启动时,组件是隐藏状态 22 private data: number[] = []; 23 24 aboutToAppear() { 25 for (let i: number = 0; i < Constants.IMAGE_TOTAL_NUM; i++) { 26 this.data.push(i); 27 } 28 } 29 30 build() { 31 Column() { 32 Button($r('app.string.reveal_the_hidden')) 33 .onClick(() => { 34 this.isVisible = !(this.isVisible); 35 }) 36 .width($r('app.string.layout_100_percent')) 37 Stack() { 38 Image($r('app.media.icon')) 39 .objectFit(ImageFit.Contain) 40 .width($r('app.string.layout_50_percent')) 41 .height($r('app.string.layout_50_percent')) 42 if (this.isVisible) { // 使用条件渲染,启动时组件处于隐藏状态,不会创建 43 Scroll() { 44 Column() { 45 ForEach(this.data, (item: number) => { 46 Text(`Item value: ${item}`) 47 .fontSize($r('app.integer.font_size_20')) 48 .width($r('app.string.layout_100_percent')) 49 .textAlign(TextAlign.Center) 50 }, (item: number) => item.toString()) 51 } 52 } 53 } 54 } 55 } 56 } 57} 58