鸿蒙开发入门零基础学鸿蒙编程ArkTS/ArkUI实战

27、鸿蒙/组件/按钮(Button)

2024-07-21  本文已影响0人  圆梦人生

Button是按钮组件,通常用于响应用户的点击操作,其类型包括胶囊按钮、圆形按钮、普通按钮。Button做为容器使用时可以通过添加子组件实现包含文字、图片等元素的按钮。具体用法请参考Button

创建按钮

Button通过调用接口来创建,接口调用有以下两种形式:

Button(label?: ResourceStr, options?: { type?: ButtonType, stateEffect?: boolean })

其中,label用来设置按钮文字,type用于设置Button类型,stateEffect属性设置Button是否开启点击效果。

Button('确定', {
       // 按钮类型
       type: ButtonType.Normal,
       // 点击效果
       stateEffect: true
})
Button(options?: {type?: ButtonType, stateEffect?: boolean})

只支持包含一个子组件,子组件可以是基础组件或者容器组件

Button({ type: ButtonType.Normal, stateEffect: true }) {
       Row() {
         Image($r('app.media.startIcon')).width(20).height(40).margin({ left: 12 })
         Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 })
       }.alignItems(VerticalAlign.Center)
}.borderRadius(8).backgroundColor(0x317aff).width(90).height(40)

设置按钮类型

Button有三种可选类型,分别为胶囊类型(Capsule)、圆形按钮(Circle)和普通按钮(Normal),通过type进行设置。

 Button('确定', {type: ButtonType.Capsule})
Button('确定', {type: ButtonType.Circle})
Button('确定', {type: ButtonType.Normal})

自定义样式

Button('确定', {type: ButtonType.Normal})
       .borderRadius(20)
Button('确定', {type: ButtonType.Normal})
       .borderRadius(20)
       .fontSize(20)
       .fontColor(Color.Red)
       .fontWeight(800)
Button('确定').backgroundColor(Color.Red)

添加事件

Button组件通常用于触发某些操作,可以绑定onClick事件来响应点击操作后的自定义行为。

 Button('点击按钮').onClick(()=>{
       console.log('按钮被点击');
})
上一篇 下一篇

猜你喜欢

热点阅读