本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新
一、Button组件基础
1. 创建方式
Button组件支持两种创建形式:
-
纯文本按钮
Button('确定', { type: ButtonType.Normal, stateEffect: true })
.width(100)
.height(40)
.backgroundColor(Color.Blue)
.fontColor(Color.White)
type
:按钮类型(默认Capsule
,此处设为Normal
关闭自动圆角)stateEffect
:是否启用点击反馈效果(默认true)
-
容器按钮(含子组件)
Button({ type: ButtonType.Capsule }) {
Row() {
Image($r('app.media.icon'))
.width(20)
.height(20)
Text('图标按钮')
.margin({ left: 5 })
}
.alignItems(VerticalAlign.Center)
}
.width(150)
.height(50)
注:仅支持单个子组件,常用于图文结合按钮
2. 按钮类型(ButtonType)
通过type
属性定义按钮形态:
-
Capsule(胶囊按钮) 圆角自动匹配高度的一半,不可通过
borderRadius
修改:
Button('提交', { type: ButtonType.Capsule })
.backgroundColor(0x317aff)
.width(120)
.height(50)
· Circle(圆形按钮) 强制宽高相等时为正圆:
Button('', { type: ButtonType.Circle })
.width(60)
.height(60)
.backgroundColor(Color.Red)
Normal(普通按钮) 默认无圆角,可自定义样式:
Button('取消', { type: ButtonType.Normal })
.borderRadius(8)
.borderWidth(1)
.borderColor(Color.Gray)
二、常用样式与交互
1. 样式配置
-
尺寸与边距
.width(100) // 宽度
.height(40) // 高度
.margin({ top: 10, bottom: 10 }) // 外边距
-
背景与边框
.backgroundColor(Color.Red) // 背景色
.borderRadius(20) // 圆角
.borderWidth(2) // 边框宽度
.borderColor(Color.Black) // 边框颜色
-
文字样式
.fontSize(16) // 字体大小
.fontColor('#FFFFFF') // 字体颜色
.fontWeight(500) // 字重
2. 事件处理
-
点击事件 通过
.onClick
绑定逻辑:
@State message: string = '点击前'
Button(this.message)
.onClick(() => {
this.message = '已点击'
})
-
动态交互 结合
@State
实现状态驱动UI更新:
@State isDisabled: boolean = false
Button('切换状态', { stateEffect: true })
.backgroundColor(this.isDisabled ? Color.Gray : Color.Blue)
.onClick(() => {
this.isDisabled = !this.isDisabled
})
三、高级用法
1. 自定义复杂按钮
通过嵌套布局组件实现图文混合按钮:
Button({ type: ButtonType.Normal }) {
Column() {
Image($r('app.media.arrow'))
.width(24)
.height(24)
Text('更多操作')
.margin({ top: 5 })
}
}
.width(120)
.height(80)
.backgroundColor(Color.Orange)
2. 其他
使用canIUse
判断API支持性:
if (canIUse('SystemCapability.ArkUI.Button.Capsule')) {
// 使用胶囊按钮特性
} else {
// 降级处理
}
禁用状态按钮:
// 禁用状态按钮
Button('禁用状态', { stateEffect: true })
.width(150)
.height(40)
.backgroundColor(Color.Gray)
.enabled(this.count % 2 !== 0) // 控制是否可点击
}
.width('100%')
.padding(20)
}