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元素,提升复用性

相关推荐
mCell1 小时前
AI 时代 SVG 画图的潜力
前端·agent·svg
我命由我123457 小时前
CesiumJS 笔记 - 获取容器中心点、Cartesian3 clone 方法、修改 Cartesian3 对象的高度
前端·javascript·css·前端框架·html·html5·js
Hopebearer_8 小时前
页面突然只剩 DOM?一次静态资源版本错配排查
前端·部署
抱抱宝8 小时前
Agent-study项目教程(03):手写 Mini-ReAct Agent(不依赖框架)
javascript·人工智能·gpt·react.js·prompt·agent
东风破_8 小时前
ESLint 是什么?为什么你的项目需要它?
前端·后端·代码规范
用户938515635078 小时前
Next.js 笔记系统(二):Redis 数据服务与侧边栏组件拆分实战
javascript·全栈
java1234_小锋9 小时前
Vue3专题 - 组件基础
vue.js·vite
圣殿骑士-Khtangc10 小时前
Go字符串高效拼接性能对比与底层原理分析
服务器·前端·golang
BigTopOne10 小时前
【ijkplayer】 硬解码流程
前端
kyriewen11 小时前
DeepSeek Harness开源第一天我就上手了——和Claude Code的差距比想象中大
前端·ai编程·deepseek