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