1

当用户单击日期时,如何显示新标记?我确定我只是缺少文档中的一些参考,但我希望能指出正确方向的指针。

我正在使用库 react-native-calendars ( https://github.com/wix/react-native-calendars ) 及其样板代码。

        <Calendar
            // Collection of dates that have to be colored in a special way. Default = {}
            markedDates={{
                '2021-05-20': {textColor: 'green'},
                '2021-05-22': {startingDay: true, color: 'green'},
                '2021-05-23': {selected: true, endingDay: true, color: 'green', textColor: 'gray'},
                '2021-05-04': {disabled: true, startingDay: true, color: 'green', endingDay: true}
            }}
            // Date marking style [simple/period/multi-dot/custom]. Default = 'simple'
            markingType={'period'}
        />

目前,当我单击日期时,没有任何反应。我猜我应该检测到点击并相应地更改markedDates dict,但我不知道该怎么做。是否有 onMarked 回调方法或我可以使用的方法?

4

1 回答 1

3

好吧,我在这里所做的是,当我单击一天时,它会标记从您单击之日到第 4 天的 4 天(这是示例,但您可以根据您的用例调整代码):

另外,我使用时刻来添加日期和格式化日期。您可以使用另一个日期库

import React, { useState } from "react";
import {Calendar} from 'react-native-calendars';
import moment from 'moment';

const App = () => {
  const [markedDates, setMarkedDates] = useState({
    '2021-01-20': {textColor: 'green'},
    '2021-01-22': {startingDay: true, color: 'green'},
    '2021-01-23': {selected: true, endingDay: true, color: 'green', textColor: 'gray'},
    '2021-01-04': {disabled: true, startingDay: true, color: 'green', endingDay: true}
  })

  const handleDayPress = (day) => {
    setMarkedDates({
      [day.dateString]: {
        startingDay: true,color: 'green'
      },
      [moment(day.dateString).add(1, 'days').format('YYYY-MM-DD')]: {
        color: 'green'
      },
      [moment(day.dateString).add(2, 'days').format('YYYY-MM-DD')]: {
        color: 'green'
      },
      [moment(day.dateString).add(3, 'days').format('YYYY-MM-DD')]: {
        endingDay: true,color: 'green'
      }
    })
  }

  return (
    <Calendar
      markedDates={markedDates}
      markingType={'period'}
      onDayPress={handleDayPress}
    />
  )
}

export default App;
于 2021-01-04T23:01:45.570 回答