数组渲染 ForEach
ForEach ( 数组 , (变量1 : string , 变量2 : number)=>{组件})
变量1 取出的数组信息 相当于 数组 [ 变量2 ]
变量2 Index 当前数组索引
简易示例 (实验)
// 对象定义
interface xs1 {
name:string,
xb:string,
age:number
}
@Entry
@Component
struct Index {
//对象数组
@State xss1 : xs1[] = [
{name:'小芳',xb:'女',age:12},
{name:'小明',xb:'男',age:11},
{name:'小刚',xb:'男',age:13},
{name:'小强',xb:'男',age:12}
]
@State mzs1 : string[] = ['asas','asdas','erwer']
build() {
Column({space:10}){
ForEach(this.xss1,(item:string,i:number)=>{
Row({space:5}){
Text(`${i} ${this.xss1[i].name}`)
Text(`${this.xss1[i].xb}`)
Text(`${this.xss1[i].age}`)
}.onClick(()=>{console.log(`为什么不引用 item 点一下就知道了 ${item}`)})
})
Button('验证1')
.onClick(()=>{
this.xss1[2].age = 10
console.log('验证1',this.xss1[2].age,)
console.log('说明即使建立的变量为状态变量 太复杂了(数组包对象)也不会引起组件刷新(重新渲染)')
})
ForEach(this.mzs1,(item2:string,i2:number)=>{
Text(`${item2}`)
})
Button('验证2')
.onClick(()=>{
this.mzs1[1] = '你好世界'
console.log('说明简易的状态数组是可以引起组件重新渲染')
})
}
}
}