学习鸿蒙基础(4)

1.条件渲染

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

当if、else if后跟随的状态判断中使用的状态变量值变化时,条件渲染语句会进行更新。。

TypeScript 复制代码
@Entry
@Component
struct PageIfElse {
  @State list: Object [] = []

  build() {
    Row() {
      Column() {
        Button("onClick").onClick(()=>{
          this.list=[
            { id: 1, name: "房子",type:1 },
            { id: 2, name: "车子",type:2 },
            { id: 3, name: "票子",type:3} ,
            { id: 1, name: "理想",type:1 },
            { id: 2, name: "现实",type:2 },
            { id: 3, name: "梦想",type:3}
          ]
        })
        if(this.list.length){
          List(){
            ForEach(this.list,(item:Object)=>{
              ListItem(){
                getOrder(item)
              }.margin(10)
            },item=>JSON.stringify(item))
          }.height(200)
        }else{
           Text("三无青年")
        }
      }
      .width('100%')
    }
    .height('100%')
  }
}

@Builder
function  getOrder(item){
  Row(){
    Text(item["name"]).fontSize(18).fontColor("#333333")
    if(item["type"]==1){
      Text("一座").fontSize(19).fontColor(Color.Red)
    }else if(item["type"]==2){
      Text("二辆").fontSize(19).fontColor(Color.Red)
    }else if(item["type"]==3){
      Text("三捆").fontSize(19).fontColor(Color.Red)
    }

  }.justifyContent(FlexAlign.SpaceBetween).width("100%")
}

2.自定义组件

在ArkUI中,UI显示的内容均为组件,由框架直接提供的称为系统组件,由开发者定义的称为自定义组件。在进行Ul界面开发时,通常不是简单的将系统组件进行组合使用,而是需要考虑代码可复用性、业务逻辑与UI分离,后续版本演进等因素。因此,将UI和部分业务逻辑封装成自定义组件是不可或缺的能力。

自定义组件具有以下特点:

1、可组合:允许开发者组合使用系统组件、及其属性和方法。

2、可重用:自定义组件可以被其他组件重用,并作为不同的实例在不同的父组件或容器中使用。

3、数据驱动UI更新:通过状态变量的改变,来驱动UI的刷新。

struct:自定义组件基于struct实现,struct +自定义组件名+..}的组合构成自定义组件,不能有继承关系。对于struct的实例化,可以省略new。

@Component: @Component装饰器仅能装饰struct关键字声明的数据结构。struct被@Component装饰后具备组件化的能力,需要实现build方法描述UI,一个struct只能被一个@Component装饰。

@Entry: @Entry装饰的自定义组件将作为UI页面的入口。在单个UI页面中,最多可以使用@Entry装饰一个自定义组件。

build()函数中需注意: build()函数用于定义自定义组件的声明式UI描述,自定义组件必须定义build()函数。

build()函数下的根节点唯一且必要,且必须为容器组件,其中ForEach禁止作为根节点。build()函数下:

1、不允许声明本地变量。

2、不允许在UI描述里直接使用console.info(),但允许在方法或者函数里使用。

3、不允许调用没有用@Builder装饰的方法。

4、不允许switch语法,如果需要使用条件判断,请使用if。

5、不允许使用表达式,比如三目运算。

代码示例:

自定义组件需要新建一个components的文件夹。将自定义组件拷贝在里面。

TypeScript 复制代码
import Item from '../model/Item';
//自定义组件  组件与组件之间是隔离的
@Component
struct myList {
  private item: Item;
  private index: number;
  private list: Item [];

  @State isChecked:boolean =false

  build() {
    Row() {
      Checkbox().onChange(v=>{
        console.log(v.toString())
        this.isChecked=v
      })
      Text(this.item.text).fontSize(20).decoration(
        {type:this.isChecked?TextDecorationType.Underline:TextDecorationType.None,
          color:Color.Blue}
      )
      Button("删除").backgroundColor(Color.Red).onClick(() => {
        this.list.splice(this.index, 1)
      })
    }.justifyContent(FlexAlign.SpaceBetween).width("100%")
  }
}

export default myList

自己新建的对象需要新建一个model文件夹。对象是普通的ts文件。

TypeScript 复制代码
class Item {
  id: number;
  text: string;

  constructor(id: number, text: string) {
    this.id = id
    this.text = text
  }
}

export  default Item

DEMO运行效果如下

自定义组件demo如下:

TypeScript 复制代码
import myList from '../components/myList'
import Item from '../model/Item'
@Entry
@Component
struct PageIfElse {
  @State text: string = ''
  @State list: Item [] = [
    new Item(Date.now(), "房子"),
    new Item(Date.now(), "车子")
  ]
  build() {
    Row() {
      Column() {
        Row() {
          TextInput({ text: this.text }).width(250).onChange((value) => {
            this.text = value
          })
          Button("增加").onClick(() => {
            this.list.push(new Item(Date.now(), this.text))
            this.text = ""
          }).margin(10)
        }.width("100%").justifyContent(FlexAlign.SpaceBetween).margin(10)

        List() {
          ForEach(this.list, (item, index) => {
            ListItem() {
              myList({ item, index, list: this.list })
            }.margin(10)
          })
        }.layoutWeight(1).divider({
          strokeWidth: 1,
          color: Color.Blue,
          startMargin: 10,
          endMargin: 10
        })
        .width('100%')
      }
    }
    .height('100%')
  }
}
相关推荐
①个程序员13 分钟前
thinkphp 学习记录
学习
alfiy1 小时前
Elasticsearch学习笔记(四) Elasticsearch集群安全配置一
笔记·学习·elasticsearch
向上的车轮1 小时前
Django学习笔记十一:部署程序
笔记·学习·django
不灭锦鲤2 小时前
ssrf学习(ctfhub靶场)
网络·学习·安全
alfiy2 小时前
Elasticsearch学习笔记(五)Elastic stack安全配置二
笔记·学习·elasticsearch
权^2 小时前
MySQL--聚合查询、联合查询、子查询、合并查询(上万字超详解!!!)
大数据·数据库·学习·mysql
冷静 包容2 小时前
C语言学习之 没有重复项数字的全排列
c语言·开发语言·学习
K3njuan2 小时前
《数据结构》学习系列
学习
结衣结衣.2 小时前
C++ 类和对象的初步介绍
java·开发语言·数据结构·c++·笔记·学习·算法
limengshi1383924 小时前
通信工程学习:什么是RIP路由信息协议
网络·网络协议·学习·智能路由器·信息与通信