OpenHarmony按钮组件使用技巧
一 创建与类型选择
// 文字按钮
Button('OK', { type: ButtonType.Normal, stateEffect: true })
.backgroundColor(0x317aff).width(90).height(40)
// 图文按钮(仅一个子组件)
Button({ type: ButtonType.Normal, stateEffect: true }) {
Row() {
Image($r('app.media.ic_loading')).width(20).height(20).margin({ left: 12 })
Text('Loading').fontSize(12).fontColor(Color.White).margin({ left: 5, right: 12 })
}.alignItems(VerticalAlign.Center)
}.backgroundColor(0x317aff).borderRadius(8).width(90).height(40)
Button('Capsule', { type: ButtonType.Capsule }).width(90).height(40) // 圆角固定
Button('Circle', { type: ButtonType.Circle }).width(90).height(90) // 必须宽高相等
Button('Normal', { type: ButtonType.Normal }).borderRadius(8) // 可自定义圆角
二 交互与状态管理
Button('Click')
.onClick((e) => {
console.info(`clicked at ${e.x}, ${e.y}`)
})
@Entry
@Component
struct Counter {
@State count: number = 0
build() {
Column() {
Button('Increment').onClick(() => { this.count++ })
Text(`Count: ${this.count}`).fontSize(20)
}
}
}
Button('Key')
.onKeyEvent((e: KeyEvent) => {
if (e.type === KeyType.Down) { /* 处理按下 */ }
if (e.type === KeyType.Up ) { /* 处理抬起 */ }
})
以上交互方式覆盖了触屏点击、状态刷新与遥控/键盘三大常见输入通道。
三 样式与布局要点
// 阻断点击冒泡
Column() {
Button('Child').enabled(false)
}
.hitTestBehavior(this.block ? HitTestMode.Block : HitTestMode.Default)
.onClick(() => { /* 父级点击 */ })
// 阻断触摸冒泡
Button('Child')
.onTouch((e) => {
e.stopPropagation()
// 处理子级触摸
})
这些实践能显著提升按钮的可点性、可访问性与复杂布局下的稳定性。
四 进阶用法与实战示例
@Entry
@Component
struct LoadingButton {
@State loading: boolean = false
@State progress: number = 0
start() {
this.loading = true; this.progress = 0
const timer = setInterval(() => {
this.progress += 10
if (this.progress >= 100) {
clearInterval(timer)
this.loading = false
this.progress = 0
}
}, 200)
}
build() {
Button(this.loading ? 'Loading' : 'Submit')
.enabled(!this.loading)
.onClick(() => this.start())
.width(120).height(40)
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。