学习鸿蒙基础(4)

目录

一、条件渲染 if else

二、自定义组件 components


一、条件渲染 if else

ArkTS提供了渲染控制的能力。条件渲染可根据应用的不同状态,使用if、else和else if渲染对应状态下的UI内容。
当if、else if后跟随的状态判断中使用的状态变量值变化时,条件渲染语句会进行更新。。

@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%")
}
二、自定义组件 components

在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的文件夹。将自定义组件拷贝在里面。


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文件。


class Item {
  id: number;
  text: string;

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

export  default Item

DEMO运行效果如下

 自定义组件demo如下:

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%')
  }
}


  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

留白的云

感谢鼓励。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值