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

相关推荐
心中无石马6 小时前
uniapp引入tailwindcss4.x
前端·css·uni-app
焰火19996 小时前
[Vue]可重置的响应式状态reactive
前端·vue.js
陆枫Larry6 小时前
CSS transform scale:图片放大效果背后的原理
前端
源码宝6 小时前
基于 SpringBoot + Vue 的医院随访系统:技术架构与功能实现
java·vue.js·spring boot·架构·源码·随访系统·随访管理
昇腾CANN6 小时前
TileLang-Ascend 算子性能优化方法与实操
开发语言·javascript·性能优化·昇腾·cann
老王以为6 小时前
为什么 React 和 Vue 不一样?
前端·vue.js·react.js
web打印社区6 小时前
2026最新Web静默打印解决方案,无插件无预览,完美替代Lodop
前端·javascript·vue.js·electron·pdf
这个DBA有点耶7 小时前
分组排名不用窗口函数?那你还在写几十行的子查询
前端·代码规范
ZhiqianXia7 小时前
《The Design of Design》阅读笔记
前端·笔记·microsoft
有马贵将7 小时前
【5】微前端知识点总结
前端·架构