【问题标题】:How to dynamically change the date for the date key in the items prop for react-native-calendars如何动态更改 react-native-calendars 的 items 道具中日期键的日期
【发布时间】:2019-10-12 06:32:54
【问题描述】:

我正在尝试更改 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;
}

此函数将日期对象转换为 Agenda 所需的“YYYY-MM-DD”形式

function dateToString (date) {
    const newString  = moment(date).format('YYYY-MM-DD');
    return newString.toString()
}

我检查了我的日期是否正确,并且他们都已签出。我还使用了currentDateday6 作为minDatemaxDateAgenda 道具的对象,它们按预期工作。

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

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

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

【问题讨论】:

    标签: javascript arrays string react-native react-native-calendars


    【解决方案1】:

    我在移动设备上,所以我无法运行此代码...

    尝试像这样返回您的日期对象:

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

    您还可以重写您的每周项目函数以从 0 迭代到 6 并动态设置将返回的对象的属性。

    比在你的组件中:

    // 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/>);}}
    />
    

    【讨论】:

    • 非常感谢。退货日期周围的 [] 有效。不过,我可以问一下,[] 在使它起作用的日期之前做了什么?
    • {day1: []} => 对象将具有键 'day1' {[day1]: []} => 对象将具有值为 'day1' 的键
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    相关资源
    最近更新 更多