焦點(diǎn)事件

2024-01-22 11:21 更新

焦點(diǎn)事件指頁面焦點(diǎn)在可獲焦組件間移動時(shí)觸發(fā)的事件,組件可使用焦點(diǎn)事件來處理相關(guān)邏輯。

說明
  • 從API Version 8開始支持。后續(xù)版本如有新增內(nèi)容,則采用上角標(biāo)單獨(dú)標(biāo)記該內(nèi)容的起始版本。

  • 目前僅支持通過外接鍵盤的tab鍵、方向鍵觸發(fā)。

  • 存在默認(rèn)交互邏輯的組件例如Button、TextInput等,默認(rèn)即為可獲焦,Text、Image等組件則默認(rèn)狀態(tài)為不可獲焦,不可獲焦?fàn)顟B(tài)下,無法觸發(fā)焦點(diǎn)事件,需要設(shè)置focusable屬性為true才可觸發(fā)。

事件

名稱支持冒泡功能描述
onFocus(event: () => void)當(dāng)前組件獲取焦點(diǎn)時(shí)觸發(fā)的回調(diào)。
onBlur(event:() => void)當(dāng)前組件失去焦點(diǎn)時(shí)觸發(fā)的回調(diào)。

示例

  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct FocusEventExample {
  5. @State oneButtonColor: string = '#FFC0CB'
  6. @State twoButtonColor: string = '#87CEFA'
  7. @State threeButtonColor: string = '#90EE90'
  8. build() {
  9. Column({ space: 20 }) {
  10. // 通過外接鍵盤的上下鍵可以讓焦點(diǎn)在三個(gè)按鈕間移動,按鈕獲焦時(shí)顏色變化,失焦時(shí)變回原背景色
  11. Button('First Button')
  12. .backgroundColor(this.oneButtonColor)
  13. .width(260)
  14. .height(70)
  15. .fontColor(Color.Black)
  16. .focusable(true)
  17. .onFocus(() => {
  18. this.oneButtonColor = '#FF0000'
  19. })
  20. .onBlur(() => {
  21. this.oneButtonColor = '#FFC0CB'
  22. })
  23. Button('Second Button')
  24. .backgroundColor(this.twoButtonColor)
  25. .width(260)
  26. .height(70)
  27. .fontColor(Color.Black)
  28. .focusable(true)
  29. .onFocus(() => {
  30. this.twoButtonColor = '#FF0000'
  31. })
  32. .onBlur(() => {
  33. this.twoButtonColor = '#87CEFA'
  34. })
  35. Button('Third Button')
  36. .backgroundColor(this.threeButtonColor)
  37. .width(260)
  38. .height(70)
  39. .fontColor(Color.Black)
  40. .focusable(true)
  41. .onFocus(() => {
  42. this.threeButtonColor = '#FF0000'
  43. })
  44. .onBlur(() => {
  45. this.threeButtonColor = '#90EE90'
  46. })
  47. }.width('100%').margin({ top: 20 })
  48. }
  49. }

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號