#跟着若城学鸿蒙# Badge角标组件开发实战
·
Badge
组件用于在目标组件上方以数字、文本或小红点的形式展示提示信息,常见于未读消息、通知角标等场景。
1. 定义
interface BadgeInterface {
(params: BadgeParamWithNumber): BadgeAttribute;
(params: BadgeParamWithString): BadgeAttribute;
}
declare interface BadgeParam {
position?: BadgePosition;
style: BadgeStyle;
}
declare interface BadgeParamWithNumber extends BadgeParam {
count: number;
maxCount?: number;
}
declare interface BadgeParamWithString extends BadgeParam {
value: string;
}
-
position
BadgePosition.Left
:左侧纵向居中BadgePosition.Right
:右侧纵向居中BadgePosition.RightTop
(默认):右上角
-
style (
BadgeStyle
)color
:文本颜色,默认#FFFFFF
fontSize
:字体大小,默认10vp
badgeSize
:角标尺寸,默认根据字体自动计算badgeColor
:背景色,默认红色
-
count(数字角标)
count
:显示的数字maxCount
:最大值,超过后显示为maxCount+
-
value(文本角标)
- 直接显示指定的字符串
2. 基本示例
2.1 小红点
Badge({
value: ' ',
position: BadgePosition.RightTop,
style: { badgeSize: 6, badgeColor: Color.Red }
}) {
Icon(Icons.Notifications)
.size({ width: 32, height: 32 });
}
2.2 文本角标
Badge({
value: 'NEW',
position: BadgePosition.RightTop,
style: {
color: Color.White,
fontSize: 12,
badgeSize: 20,
badgeColor: Color.Blue
}
}) {
Text("专题")
.fontSize(16)
.padding({ horizontal: 12, vertical: 6 });
}
2.3 数字角标
Badge({
count: 42,
maxCount: 99,
position: BadgePosition.RightTop,
style: {
color: Color.White,
fontSize: 12,
badgeSize: 20,
badgeColor: Color.Red
}
}) {
Button("消息")
.size({ width: 100, height: 48 });
}
3. 进阶用法
3.1 自动溢出
超过 maxCount
时自动显示 maxCount+
:
Badge({
count: 120,
maxCount: 99,
position: BadgePosition.RightTop,
style: { badgeColor: Color.Red }
}) { /* ... */ }
3.2 动态交互
结合状态管理,实现动态更新:
@Entry @Component
struct BadgeInteractive {
@State count: number = 0;
build() {
Column({ space: 20, alignItems: HorizontalAlign.Center }) {
Badge({
count: this.count,
maxCount: 99,
style: { color: Color.White, fontSize: 12, badgeColor: Color.Red }
}) {
Button("增加")
.onClick(() => { this.count += 1; })
.size({ width: 100, height: 50 });
}
}
.padding(30);
}
}
4. API 小结
参数 | 类型 | 说明 |
---|---|---|
count |
number |
数字角标值 |
maxCount |
number |
最大显示值,超过显示 maxCount+ |
value |
string |
文本角标内容 |
position |
BadgePosition |
角标位置 |
style |
BadgeStyle |
颜色、大小、字体等样式 |
5. 总结
- 一行代码包裹:将
Badge(...) { 子组件 }
用于任意组件 - 灵活配置:数字/文本/小红点;位置、大小、颜色全可定制
- 结合状态:动态更新角标,提升用户体验
使用 Badge
,为您的应用增添清晰可见的消息提示,与用户实时互动。
更多推荐
所有评论(0)