ArkTs核心语法

if分支语句

复制代码
let name:string='人'
if(name=='人'){
  console.log('name是人不是狗');
}else if(name=='狗'){
  console.log('name是人不是狗');
}else {
  console.log('name不是人');
}

条件表达式

复制代码
条件?成立表达式1:不成立表达式2

let num1:number=1
let num2:number=2
let flag = (num1<num2 ? 'num1<num2' : 'num1num2')
console.log('flag--',flag);

条件渲染

根据逻辑条件结果不同,渲染不用的UI内容

复制代码
let name:string='人'

@Entry
@Component
struct Index{
  build() {
   Column(){
     if(name=='人'){
       Text('name是人不是狗')
     }else if(name=='狗'){
       Text('name是人不是狗')
     }else {
       Text('name不是人')
     }
   }
  }
}

循环渲染

根据数组数据重复渲染UI内容

ForEach(数组,(item:类型,index:number)=>{})

复制代码
let names:string[]=['张三','李四','王五']

@Entry
@Component
struct Index{
  build() {
   Column(){
     ForEach(names,(item:string,index:number)=>{
       Text(item+index)
     })
   }
  }
}

状态管理

应用的运行时的状态参数,当参数改变时,UI渲染刷新

状态变量:用装饰器修饰的变量,使用变量的地方会刷新

复制代码
@ComponentV2

状态值@Local修饰

组件关联状态值 .onClick(()=>{this.num-- })

使用状态值要用this.调用

复制代码
@Entry
@ComponentV2
struct Index{
  @Local num:number=1;

  build() {
    Column(){
      Row(){
        Text('-')
          .width(40)
          .height(40)
          .border({width:1,color:'#999',radius:{topLeft:3,bottomLeft:3}})
          .textAlign(TextAlign.Center)
          .onClick(()=>{
            if (this.num>1) {
              this.num--
            }
          })
        Text(this.num.toString())
          .width(40)
          .height(40)
          .border({width:1,color:'#999'})
          .textAlign(TextAlign.Center)
        Text('+')
          .width(40)
          .height(40)
          .border({width:1,color:'#999',radius:{topRight:3,bottomRight:3}})
          .textAlign(TextAlign.Center)
          .onClick(()=>{
            this.num++
          })
      }

    }
  }
}

@Buider自定义构建函数

用于封装需要重复使用的UI元素,提升复用性

相关推荐
计算机魔术师1 小时前
美国司法部正式站队 OpenAI,AI 训练的版权账要这么算了
前端
IT_陈寒1 小时前
React Hooks闭包陷阱差点让我加班到凌晨
前端·人工智能·后端
风骏时光牛马1 小时前
疑难Bug根因定位与问题复盘分析
前端
创新技术阁2 小时前
FastapiAdmin 系统日志体系与核心配置参数详解
前端·后端·fastapi
掘金酱2 小时前
【社区公告】签到与矿石奖励解耦说明
前端
promiseThen2 小时前
LWC Workflow:用 7 个 Cursor Skill 搭一条 AI 协作开发流水线
前端·ai编程
一个游离的指针3 小时前
函数管道:消除深度嵌套调用
前端·javascript
浅诺3 小时前
Nginx sub_filter 的“幽灵陷阱”:为什么页面能打开,懒加载的 JS 却全是 404?
前端
PBitW3 小时前
为什么vite中TS报错,可以继续运行?Webpack不行?
前端·webpack·typescript·vite
光影少年3 小时前
react navite手写 FlatList 优化配置
前端·react native·react.js