HarmonyOS-用ForEach实现日历选中
ForEach语法
ForEach基于数组类型数据来进行循环渲染,需要与容器组件配合使用,且接口返回的组件应当是允许包含在ForEach父容器组件中的子组件。例如,ListItem组件要求ForEach的父容器组件必须为List组件.
- 语法: ForEach**(arr, (item, index) => {})**
ForEach基于数组类型数据来进行循环渲染,需要与容器组件配合使用,且接口返回的组件应当是允许包含在ForEach父容器组件中的子组件。例如,ListItem组件要求ForEach的父容器组件必须为List。GridItem组件要求ForEach的父容器组件为Grid。
例如:
这种重复的代码就可以用ForEach来节省代码量
如图:
完整代码:
@Entry
@Component
struct Index {
//定义一个数组用来存储日期
@State list: number[] = Array.from(Array(31), (_: number, index: number) => {
return index + 1
})
@State date: number = 1
build() {
Column() {
Grid() {
ForEach(this.list, (item: number) => {
//this.list, 根据该数组生成对应的UI组件渲染到页面中:可以为空数组
//item: 代表每一个数组元素, 类型与数组元素保持一致,不可以省略
GridItem() {
//这里Text只能接受字符串,但可以通过toString来转换
Text(item.toString())
.fontColor(this.getFontColor(item))
.backgroundColor(this.getColor(item))
.width(30)
.aspectRatio(1)
.textAlign(TextAlign.Center)
//点击事件
.onClick(() => {
//点击的数组元素赋值给date,默认为1
this.date = item
})
}
})
}
.columnsTemplate("1fr 1fr 1fr 1fr 1fr 1fr 1fr")
}
}
//构建函数获取字体颜色,背景颜色
getColor(item: number) {
//当点击的时间与item元素相等时
if (this.date === item) {
return "#d72626"
} else {
//否则
return "#ffffff"
}
}
getFontColor(item: number) {
//当点击的时间与item元素相等时
if (this.date === item) {
console.log("", this.date);
return "#ffffff"
} else {
//否则
return "#2b2b2b"
}
}
}
最后效果: