如何动态更改 react-native-calendars 项目道具中日期键的日期

How to dynamically change the date for the date key in the items prop for react-native-calendars

我正在尝试更改 items 道具中的日期以响应本机日历。 从文档中可以看出,它需要一个日期字符串作为键,然后需要一个对象数组来显示该特定日期。

像这样。

<Agenda
    items: {{
        '2019-10-12': [],
        '2019-10-13': [{}, {}],
        '2019-10-14': [{}],
        '2019-10-15': []
    }}
/>

但是,我不想对日期进行硬编码。我想要的是显示下周的日期。这是我试过的方法

我使用

获取日期
 new currentDate = new Date();

我将这个日期传递给每周项目以获取我的每周项目对象。 下面的函数使用另外两个函数 addDaysdateToString 来正确呈现日期。

const weeklyItems = (date) => {
    const day1 = dateToString(addDays(date, 1));
    const day2 = dateToString(addDays(date, 2));
    const day3 = dateToString(addDays(date, 3));
    const day4 = dateToString(addDays(date, 4));
    const day5 = dateToString(addDays(date, 5));
    const day6 = dateToString(addDays(date, 6));
    const currentDate = dateToString(date);
    return {
        currentDate : [],
        day1: [],
        day2: [],
        day3: [],
        day4: [],
        day5: [],
        day6: []
    }
}

addDaysdateToString 是我的辅助函数:

function addDays(date, days) {
    var result = new Date(date);
    result.setDate(result.getDate() + days);
    return result;
}

此函数将日期对象转换为 'YYYY-MM-DD' 形式,这是 Agenda

所要求的形式
function dateToString (date) {
    const newString  = moment(date).format('YYYY-MM-DD');
    return newString.toString()
}

我检查过我的日期是否正确,他们都退房了。我还使用 currentDateday6 作为 minDatemaxDate 属性的对象 Agenda 并且它们按预期工作。

完成此操作后,我的 Agenda 现在看起来像这样:

 <Agenda
    minDate = {currentDate}
    maxDate = {day6}
    selected = {currentDate}
    items: {weeklyItems(currentDate)}
    renderEmptyDate={() => {return (<View/>);}}
/>

这使它停止工作。我知道我的 weeklyItems 中有空数组,但现在我只是想让日期正常工作,不幸的是它们没有。任何帮助将不胜感激。

我在手机上,所以我不能运行这个代码...

尝试 return 你的日期对象是这样的:

return {
    [currentDate] : [],
    [day1]: [],
    ...
}

您还可以重写 weeklyItems 函数以从 0 迭代到 6 并将属性动态设置为将 returned 的对象。

比你的组件:

// somewhere in your js
// const dates = weeklyItems(currentDate)
// const minDate = dateToString(date)
// const maxDate = dateToString(addDays(date, 6))

<Agenda
  minDate = {minDate}
  maxDate = {maxDate}
  selected = {minDate}
  items: {dates}
  renderEmptyDate={() => {return (<View/>);}}
/>