分享在鸿蒙使用日历组件以及事件使用和一些应用场景

279 阅读2分钟

基础使用:

1.首先在终端进行下载

ohpm install @ohmos/calendar

2.终端下载完之后 , oh_modules/@ohmos/calendar/README.md 里面查看使用说明

image.png

3.通过文档 使用日历组件

3.1进行导入

import { HmCalendar } from '@ohmos/calendar'

3.2build里面使用

HmCalendar({
  color: '#0094ff',
  selectedDays: [
    { date: '2024-05-01' },
    { date: '2024-05-10' },
    { date: '2024-05-20' },
  ]
})
  .borderRadius(8)
  .border({ width: 0.5, color: '#ededed' })
  .shadow({ color: '#ededed', radius: 16 })

得到的效果:

image.png

这样我们以后需要做打卡功能,只需要从接口中 获取对应格式的数据 传递给selectedDay就能达到效果了

观察文档,发现有两个事件, 分别是

onClickDate 和 onChangeMonth 事件

onClickDate代码:

书写位置 和 selectedDays同级 , onChangeMonth也一样

import { promptAction } from '@kit.ArkUI'

HmCalendar({
  color: '#0094ff',
  selectedDays: [
    { date: '2024-05-01' },
    { date: '2024-05-10' },
    { date: '2024-05-20' },
  ],
    onClickDate: (currentDate: string) => {
      promptAction.showToast({ message: currentDate })//使用promptAction弹窗需要导入
    }
})

事件效果: 点击5.17 发现拿到的数据是和selectedDays里每一个对象的data的key值一样的,所以 我们可以针对某些特别的日子,进行一些弹窗提示操作等, 就像日历黄历这些等

image.png

onChangeMonth事件:

onChangeMonth会在我们切换月份, 也就是最上方2024-05 两边的按钮的时候触发,我们可以通过onChangeMonth事件在切换月份的时候进行之前月份打卡数据的显示等操作 代码:

HmCalendar({
  color: '#0094ff',
  selectedDays:this.clockInDay,
    onClickDate: (currentDate: string) => {
      promptAction.showToast({ message: currentDate })
    },
  onChangeMonth: (date: string) => {
    promptAction.showToast({ message: date })
  }
})

点击左侧切换,效果:

image.png

模拟切换月份显示打卡数据代码:

import { HmCalendar } from '@ohmos/calendar'
import { promptAction } from '@kit.ArkUI';

interface  clockIn{
  date:string
}
@Entry
@Component
struct Index {
  @State clockInDay:clockIn[]=[
    { date: '2024-05-01' },
    { date: '2024-05-10' },
    { date: '2024-05-20' },
  ]
  //静态数据,模仿切换至4月得到的数据
  clockInDay2:clockIn[]=[
    { date: '2024-04-11' },
    { date: '2024-04-13' },
    { date: '2024-04-15' },
    { date: '2024-04-25' },
  ]


  build() {
    Row() {
      Column() {
        Row(){
          HmCalendar({
            color: '#0094ff',
            selectedDays:this.clockInDay,
            // 点击日期,currentDate代表当前点击 2024-05-01
            onClickDate: (currentDate: string) => {
              promptAction.showToast({ message: currentDate })
            },
            //点击月份,date表示当前点击的年月 2024-04
            onChangeMonth: (date: string) => {
              this.clockInDay = this.clockInDay2
            },
          })
            .borderRadius(8)
            .border({ width: 0.5, color: '#ededed' })
            .shadow({ color: '#ededed', radius: 16 })
        }
      }
      .width('100%')
    }
    .height('100%')
  }
}

效果:

image.png