@Entry
@Component
struct workA {
// 定义6种颜色数组,使用ResourceColor类型确保颜色值合法性
@State color: ResourceColor[] = ['#ef2816', '#f0a200', '#6ab002', '#005868', '#41192e', '#141411']
// 定义公共样式装饰器,避免重复样式代码
@Styles
ys() {
// 白色圆形基础样式(宽高20,圆角10,白色背景)
.width(20)
.height(20)
.borderRadius(10)
.backgroundColor('#fff')
}
build() {
Column() {
/* 第一行:3个Flex容器(1-3号元素) */
Row() {
ForEach([1, 2, 3], (item: number) => {
Flex({
// 布局规则:
// 第一个元素居中排列(横向),其余元素两端分布(纵向)
justifyContent: item == 1 ? FlexAlign.Center : FlexAlign.SpaceBetween,
alignItems: item == 1 ? ItemAlign.Center : ItemAlign.Auto,
direction: item == 1 ? FlexDirection.Row : FlexDirection.Column
}) {
// 根据item值动态生成子元素
if (item == 1) {
// 情况1:单个居中圆圈
Text().ys()
} else if (item == 2) {
// 情况2:两个圆圈(右端对齐 + 默认位置)
Text().ys().alignSelf(ItemAlign.End)
Text().ys()
} else {
// 情况3:三个圆圈(右端对齐 + 居中 + 默认位置)
Text().ys().alignSelf(ItemAlign.End)
Text().ys().alignSelf(ItemAlign.Center)
Text().ys() // 注意:这里保持与上方样式一致
}
}
// 容器基础样式
.width(100)
.height(100)
.borderRadius(10)
.padding(10)
// 根据索引取颜色(item-1对应数组下标)
.backgroundColor(this.color[item - 1])
})
}
/* 第二行:3个Flex容器(4-6号元素) */
Row() {
ForEach([4, 5, 6], (item: number) => {
Flex({
// 统一使用两端对齐布局
justifyContent: FlexAlign.SpaceBetween
}) {
if (item == 4) {
// 情况4:两列,每列两个上下分布的圆圈
Column() {
Text().ys()
Text().ys()
}
.height('100%')
.justifyContent(FlexAlign.SpaceBetween)
Column() {
Text().ys()
Text().ys()
}
.height('100%')
.justifyContent(FlexAlign.SpaceBetween)
} else if (item == 5) {
// 情况5:三列(两端列2个圆圈,中间列1个居中圆圈)
Column() {
Text().ys()
Text().ys()
}
.height('100%')
.justifyContent(FlexAlign.SpaceBetween)
Column() {
Text().ys()
}
.height('100%')
.justifyContent(FlexAlign.Center)
Column() {
Text().ys()
Text().ys()
}
.height('100%')
.justifyContent(FlexAlign.SpaceBetween)
} else {
// 情况6:两列,每列三个均匀分布的圆圈
Column() {
Text().ys()
Text().ys()
Text().ys()
}
.height('100%')
.justifyContent(FlexAlign.SpaceBetween)
Column() {
Text().ys()
Text().ys()
Text().ys()
}
.height('100%')
.justifyContent(FlexAlign.SpaceBetween)
}
}
// 容器基础样式
.width(100)
.height(100)
.borderRadius(10)
.padding(10)
// 根据索引取颜色(注意数组下标从0开始)
.backgroundColor(this.color[item - 1])
})
}
}
// 页面整体样式
.padding(30) // 外围留白30vp
.backgroundColor("#eee") // 灰色背景
.width('100%') // 撑满父容器
.height(300) // 固定高度300vp
}
}
效果图如下:

309

被折叠的 条评论
为什么被折叠?



