【HarmonyOS】HarmonyOS NEXT学习日记:六、渲染控制、样式&结构重用

【HarmonyOS】HarmonyOS NEXT学习日记:六、渲染控制、样式&结构重用

渲染控制包含了条件渲染和循环渲染,所谓条件渲染,即更具状态不同,选择性的渲染不同的组件。

而循环渲染则是用于列表之内的、多个重复元素组成的结构中。

在声明式描述语句中开发者除了使用系统组件外,还可以使用渲染控制语句来辅助UI的构建,这些渲染控制语句包括控制组件是否显示的条件渲染语句,基于数组数据快速生成组件的循环渲染语句,针对大数据量场景的数据懒加载语句,针对混合模式开发的组件渲染语句。

渲染控制

条件渲染(if/else)

ArkTS提供了渲染控制的能力。条件渲染可根据应用的不同状态,使用if、else和else if渲染对应状态下的UI内容。

ts 复制代码
@Entry
@Component
struct Index {
  @State counter: number = 0;
  build() {
    Column({space: 10}){
      Text(`counter=${this.counter}`)
      Row(){
        if(this.counter===0){
          Text(`counter===0,不展示归零按钮`);
        }else{
          Button('归零').onClick(()=>{
            this.counter=0
          })
        }
      }
      Row(){
        Button('counter++')
          .onClick(()=>{
            this.counter++
          })
      }
    }
  }
}

上文我们实现了一个例子、初始化counter为0,提供一个counter++的按钮,点击时counter+1。

当counter=0时,显示文字:counter=0,不展示归零按钮

否则,展示一个归零按钮

点击归零按钮后,counter赋值0,页面回归初始状态

通过这个例子,就简单掌握了条件渲染的用法。

循环渲染

ForEach接口基于数组类型数据来进行循环渲染,需要与容器组件配合使用,且接口返回的组件应当是允许包含在ForEach父容器组件中的子组件。例如,ListItem组件要求ForEach的父容器组件必须为List组件。

用法:

ts 复制代码
// Index.ets
import text from '@ohos.graphics.text';

interface newItem{
  title: string,
  subTitle: string,
  time: string
}

@Entry
@Component
struct Index {
  @State news: newItem[] = [
    {
      title: '新闻标题1',
      subTitle: '这是一个副标题1',
      time: '2024/7/22'
    },
    {
      title: '新闻标题2',
      subTitle: '这是一个副标题2',
      time: '2024/7/22'
    },
    {
      title: '新闻标题3',
      subTitle: '这是一个副标题3',
      time: '2024/7/22'
    }
  ];
  build() {
    Scroll(){
      Column({space:1}){
        ForEach(this.news,(item:newItem)=>{
          Column(){
            Row(){
              Text(item.title)
                .fontSize(22)
            }
            .width('100%')
            Row(){
              Text(item.subTitle)
                .fontColor('#aaa')
            }
            .width('100%')
            Row(){
              Text(item.time)
                .fontColor('#aaa')
            }
            .width('100%')
            .justifyContent(FlexAlign.End)
          }
          .padding(10)
          .border({
            width: {
              bottom: 1
            },
            color: '#ccc',
            style: BorderStyle.Dashed,
          })
          .backgroundColor('rgba(25, 159, 126, 0.1)')
        },(item:newItem,index:number)=>index+'')
      }
      .width('100%')
      .backgroundColor('#eee')
    }
  }
}

样式&结构重用

@Extend:扩展组件(样式、事件)

继承一个组件并且为其添加扩展方法,通过自定义扩展方法就可以添加可复用的样式和事件。

ts 复制代码
// Index.ets
import text from '@ohos.graphics.text';
@Extend(Text)
function textExtend(backgroundColor: ResourceColor,text: string){
  .textAlign(TextAlign.Center)
  .backgroundColor(backgroundColor)
  .fontColor(Color.Red)
  .fontSize(22)
  .width('100%')
  .onClick(() => {
    AlertDialog.show({
      message: text
    })
  })
}
@Entry
@Component
struct Index {
  build() {
    Column(){
      Text('1111')
        .textExtend(Color.Blue,'1111')
      Text('2222')
        .textExtend(Color.Green,'2222')
    }
  }
}

可以看到我们布局时的代码简练了很多

![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/56c54cc368704ec7b19409557a6320da.png![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/d976cd43e0304160a2b4dca233a799aa.png)


!!!会影响整个页面的该组件,需要注意!!!

@Styles: 抽取通用属性、事件

bash 复制代码
// Index.ets
//'CommonAttribute' 类型
@Styles function textStyle() {
    .backgroundColor('#eee')
    .width('100%')
    .onClick(() => {
      AlertDialog.show({
        message: '点击触发'
      })
    })
}
@Entry
@Component
struct Index {
  build() {
    Column(){
      Text('1111')
        .textStyle()
        .textAlign(TextAlign.Center)
      Text('2222')
        .textStyle()
        .textAlign(TextAlign.Center)
    }
  }
}


特点:

  • 只能设置CommonAttribute类型的属性,也就是通用属性
    像是,TextFont这种只能给Text组件设置的属性无法通过这种方式提取。
  • 无法接收参数
  • 有组件作用域和全局作用域

@Builder:自定义构建函数(结构、样式、事件)

通过@Builder我们可以自定义构建函数,将需要复用的结构、样式、事件通通封装起来。

ts 复制代码
// Index.ets
import text from '@ohos.graphics.text'

@Builder function TextItem(text: string){
  Text(text)
    .fontSize(18)
    .fontColor(Color.Red)
    .backgroundColor('#ccc')
    .lineHeight(30)
    .width('100%')
    .textAlign(TextAlign.Center)
    .onClick(()=>{
      AlertDialog.show({
        message: text
      })
    })
}
@Entry
@Component
struct Index {
  build() {
    Column(){
      TextItem('111')
      TextItem('222')
      TextItem('333')
    }
  }
}

点击后可以触发事件

相关推荐
奔跑吧 android5 分钟前
【android bluetooth 协议分析 07】【SDP详解 2】【SDP 初始化】
android·bluetooth·aosp15·bt·gd·sdp_init
梦否2 小时前
Android 代码热度统计(概述)
android
Georgewu5 小时前
【HarmonyOS】元服务入门详解 (一)
harmonyos
西西西仓鼠6 小时前
python学习打卡:DAY 40 训练和测试的规范写法
学习
Magnetic_h6 小时前
【iOS】方法与消息底层分析
笔记·学习·macos·ios·objective-c·cocoa
xchenhao6 小时前
基于 Flutter 的开源文本 TTS 朗读器(支持 Windows/macOS/Android)
android·windows·flutter·macos·openai·tts·朗读器
今天背单词了吗9806 小时前
算法学习笔记:19.牛顿迭代法——从原理到实战,涵盖 LeetCode 与考研 408 例题
笔记·学习·算法·牛顿迭代法
coder_pig6 小时前
跟🤡杰哥一起学Flutter (三十五、玩转Flutter滑动机制📱)
android·flutter·harmonyos
DKPT7 小时前
Java设计模式之行为型模式(观察者模式)介绍与说明
java·笔记·学习·观察者模式·设计模式
消失的旧时光-19437 小时前
OkHttp SSE 完整总结(最终版)
android·okhttp·okhttp sse