1# 按钮 (Button)
2
3
4Button是按钮组件,通常用于响应用户的点击操作,其类型包括胶囊按钮、圆形按钮、普通按钮。Button做为容器使用时可以通过添加子组件实现包含文字、图片等元素的按钮。具体用法请参考[Button](../reference/apis-arkui/arkui-ts/ts-basic-components-button.md)。
5
6
7## 创建按钮
8
9Button通过调用接口来创建,接口调用有以下两种形式:
10
11
12- 创建不包含子组件的按钮。
13
14  ```ts
15  Button(label?: ResourceStr, options?: { type?: ButtonType, stateEffect?: boolean })
16  ```
17
18  其中,label用来设置按钮文字,type用于设置Button类型,stateEffect属性设置Button是否开启点击效果。
19
20  ```ts
21  Button('Ok', { type: ButtonType.Normal, stateEffect: true })
22    .borderRadius(8)
23    .backgroundColor(0x317aff)
24    .width(90)
25    .height(40)
26  ```
27
28  ![zh-cn_image_0000001562820757](figures/zh-cn_image_0000001562820757.png)
29
30
31- 创建包含子组件的按钮。
32
33  ```ts
34  Button(options?: {type?: ButtonType, stateEffect?: boolean})
35  ```
36
37  只支持包含一个子组件,子组件可以是基础组件或者容器组件。
38
39  ```ts
40  Button({ type: ButtonType.Normal, stateEffect: true }) {
41    Row() {
42      Image($r('app.media.loading')).width(20).height(40).margin({ left: 12 })
43      Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 })
44    }.alignItems(VerticalAlign.Center)
45  }.borderRadius(8).backgroundColor(0x317aff).width(90).height(40)
46  ```
47
48  ![zh-cn_image_0000001511421216](figures/zh-cn_image_0000001511421216.png)
49
50
51## 设置按钮类型
52
53Button有三种可选类型,分别为胶囊类型(Capsule)、圆形按钮(Circle)和普通按钮(Normal),通过type进行设置。
54
55
56- 胶囊按钮(默认类型)。
57
58  此类型按钮的圆角自动设置为高度的一半,不支持通过borderRadius属性重新设置圆角。
59
60  ```ts
61  Button('Disable', { type: ButtonType.Capsule, stateEffect: false })
62    .backgroundColor(0x317aff)
63    .width(90)
64    .height(40)
65  ```
66
67  ![zh-cn_image_0000001511421208](figures/zh-cn_image_0000001511421208.png)
68
69
70- 圆形按钮。
71
72  此类型按钮为圆形,不支持通过borderRadius属性重新设置圆角。
73
74  ```ts
75  Button('Circle', { type: ButtonType.Circle, stateEffect: false })
76    .backgroundColor(0x317aff)
77    .width(90)
78    .height(90)
79  ```
80
81  ![zh-cn_image_0000001511740428](figures/zh-cn_image_0000001511740428.png)
82
83- 普通按钮。
84
85  此类型的按钮默认圆角为0,支持通过borderRadius属性重新设置圆角。
86
87  ```ts
88  Button('Ok', { type: ButtonType.Normal, stateEffect: true })
89    .borderRadius(8)
90    .backgroundColor(0x317aff)
91    .width(90)
92    .height(40)
93  ```
94
95  ![zh-cn_image_0000001563060641](figures/zh-cn_image_0000001563060641.png)
96
97
98## 自定义样式
99
100- 设置边框弧度。
101
102  使用通用属性来自定义按钮样式。例如通过borderRadius属性设置按钮的边框弧度。
103
104  ```ts
105  Button('circle border', { type: ButtonType.Normal })
106    .borderRadius(20)
107    .height(40)
108  ```
109
110  ![zh-cn_image_0000001511900392](figures/zh-cn_image_0000001511900392.png)
111
112
113- 设置文本样式。
114
115  通过添加文本样式设置按钮文本的展示样式。
116
117  ```ts
118  Button('font style', { type: ButtonType.Normal })
119    .fontSize(20)
120    .fontColor(Color.Pink)
121    .fontWeight(800)
122  ```
123
124  ![zh-cn_image_0000001511580828](figures/zh-cn_image_0000001511580828.png)
125
126
127- 设置背景颜色。
128
129  添加backgroundColor属性设置按钮的背景颜色。
130
131  ```ts
132  Button('background color').backgroundColor(0xF55A42)
133  ```
134
135  ![zh-cn_image_0000001562940477](figures/zh-cn_image_0000001562940477.png)
136
137
138- 创建功能型按钮。
139
140  为删除操作创建一个按钮。
141
142  ```ts
143  let MarLeft: Record<string, number> = { 'left': 20 }
144  Button({ type: ButtonType.Circle, stateEffect: true }) {
145    Image($r('app.media.ic_public_delete_filled')).width(30).height(30)
146  }.width(55).height(55).margin(MarLeft).backgroundColor(0xF55A42)
147  ```
148
149  ![zh-cn_image_0000001511740436](figures/zh-cn_image_0000001511740436.png)
150
151
152## 添加事件
153
154Button组件通常用于触发某些操作,可以绑定onClick事件来响应点击操作后的自定义行为。
155
156```ts
157Button('Ok', { type: ButtonType.Normal, stateEffect: true })
158  .onClick(()=>{
159    console.info('Button onClick')
160  })
161```
162
163
164## 场景示例
165
166- 用于启动操作。
167
168  可以用按钮启动任何用户界面元素,按钮会根据用户的操作触发相应的事件。例如,在List容器里通过点击按钮进行页面跳转。
169
170  ```ts
171  // xxx.ets
172  @Entry
173  @Component
174  struct ButtonCase1 {
175    pathStack: NavPathStack = new NavPathStack();
176
177    @Builder
178    PageMap(name: string) {
179      if (name === "first_page") {
180        pageOneTmp()
181      } else if (name === "second_page") {
182        pageTwoTmp()
183      } else if (name === "third_page") {
184        pageThreeTmp()
185      }
186    }
187
188    build() {
189      Navigation(this.pathStack) {
190        List({ space: 4 }) {
191          ListItem() {
192            Button("First").onClick(() => {
193              this.pathStack.pushPath({ name: "first_page"})
194            })
195              .width('100%')
196          }
197
198          ListItem() {
199            Button("Second").onClick(() => {
200              this.pathStack.pushPath({ name: "second_page"})
201            })
202              .width('100%')
203          }
204
205          ListItem() {
206            Button("Third").onClick(() => {
207              this.pathStack.pushPath({ name: "third_page"})
208            })
209              .width('100%')
210          }
211        }
212        .listDirection(Axis.Vertical)
213        .backgroundColor(0xDCDCDC).padding(20)
214      }
215      .mode(NavigationMode.Stack)
216      .navDestination(this.PageMap)
217    }
218  }
219
220  // pageOne
221  @Component
222  export struct pageOneTmp {
223    pathStack: NavPathStack = new NavPathStack();
224
225    build() {
226      NavDestination() {
227        Column() {
228          Text("first_page")
229        }.width('100%').height('100%')
230      }.title("pageOne")
231      .onBackPressed(() => {
232        const popDestinationInfo = this.pathStack.pop() // 弹出路由栈栈顶元素
233        console.log('pop' + '返回值' + JSON.stringify(popDestinationInfo))
234        return true
235      })
236      .onReady((context: NavDestinationContext) => {
237        this.pathStack = context.pathStack
238      })
239    }
240  }
241
242  // pageTwo
243  @Component
244  export struct pageTwoTmp {
245    pathStack: NavPathStack = new NavPathStack();
246
247    build() {
248      NavDestination() {
249        Column() {
250          Text("second_page")
251        }.width('100%').height('100%')
252      }.title("pageTwo")
253      .onBackPressed(() => {
254        const popDestinationInfo = this.pathStack.pop() // 弹出路由栈栈顶元素
255        console.log('pop' + '返回值' + JSON.stringify(popDestinationInfo))
256        return true
257      })
258      .onReady((context: NavDestinationContext) => {
259        this.pathStack = context.pathStack
260      })
261    }
262  }
263
264  // pageThree
265  @Component
266  export struct pageThreeTmp {
267    pathStack: NavPathStack = new NavPathStack();
268
269    build() {
270      NavDestination() {
271        Column() {
272          Text("third_page")
273        }.width('100%').height('100%')
274      }.title("pageThree")
275      .onBackPressed(() => {
276        const popDestinationInfo = this.pathStack.pop() // 弹出路由栈栈顶元素
277        console.log('pop' + '返回值' + JSON.stringify(popDestinationInfo))
278        return true
279      })
280      .onReady((context: NavDestinationContext) => {
281        this.pathStack = context.pathStack
282      })
283    }
284  }
285  ```
286
287  ![zh-cn_image_0000001562700393](figures/zh-cn_image_0000001562700393.png)
288
289
290- 用于提交表单。
291
292  在用户登录/注册页面,使用按钮进行登录或注册操作。
293
294  ```ts
295  // xxx.ets
296  @Entry
297  @Component
298  struct ButtonCase2 {
299    build() {
300      Column() {
301        TextInput({ placeholder: 'input your username' }).margin({ top: 20 })
302        TextInput({ placeholder: 'input your password' }).type(InputType.Password).margin({ top: 20 })
303        Button('Register').width(300).margin({ top: 20 })
304          .onClick(() => {
305            // 需要执行的操作
306          })
307      }.padding(20)
308    }
309  }
310  ```
311
312  ![zh-cn_image_0000001562940473](figures/zh-cn_image_0000001562940473.png)
313
314- 悬浮按钮。
315
316  在可以滑动的界面,滑动时按钮始终保持悬浮状态。
317
318  ```ts
319  // xxx.ets
320  @Entry
321  @Component
322  struct HoverButtonExample {
323    private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
324    build() {
325      Stack() {
326        List({ space: 20, initialIndex: 0 }) {
327          ForEach(this.arr, (item:number) => {
328            ListItem() {
329              Text('' + item)
330                .width('100%').height(100).fontSize(16)
331                .textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
332            }
333          }, (item:number) => item.toString())
334        }.width('90%')
335        Button() {
336          Image($r('app.media.ic_public_add'))
337            .width(50)
338            .height(50)
339        }
340        .width(60)
341        .height(60)
342        .position({x: '80%', y: 600})
343        .shadow({radius: 10})
344        .onClick(() => {
345          // 需要执行的操作
346        })
347      }
348      .width('100%')
349      .height('100%')
350      .backgroundColor(0xDCDCDC)
351      .padding({ top: 5 })
352    }
353  }
354  ```
355
356  ![floating_button](figures/floating_button.gif)
357