本文介绍了在 react-native-calendar 中动态标记日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我从 api 调用中获得的 react-native-calendars 中标记日期.有人可以帮忙吗?

I'am trying to mark dates in react-native-calendars that i get from an api call. Can someone please help?

<Calendar
markingType={'multi-dot'}
markedDates={this.state.dates}
/>

在构造函数中,我正在维护

In constructor, I am maintaining

this.state = {dates : []}

我调用了函数标记(),我在其中映射数据并将日期推入另一个数组,然后执行 setState 为

I have invoked the function marked() where I am mapping over the data and pushing the dates into another array and then doing a setState as

this.setState({ 
    dates : {
        [attendance] : [
            { 
                key: 'vacation', 
                color: 'blue', 
                selectedDotColor: 'red' 
            }
        ]
    }
})

我正在分享我可以随意使用的代码.P.S:我是新手.万分感谢

I'am sharing the code I am at liberty to. P.S : I'am new to this.Thanks in andvance

推荐答案

实际上我最近不得不用 react-native-calendars 做同样的事情.这是我编写的用于创建标记日期的函数的简化版本:

I actually had to do the exact same thing recently with react-native-calendars. Here is a simplified version of the function I wrote to create marked dates:

 createMarkedDates = (dates) => {
    let markedEvents = {};
    let numEvents = {};
    let uniqueDates = [...new Set(dates)]; //remove duplicate event dates

    dates.forEach(function (count) { //if multiple events on one date, determine how many events are on each date
        numEvents[count] = (numEvents[count] || 0) + 1;
    });
        uniqueDates.forEach(function (date) {
            let dots = [];
            let markedData = {};
            for (let i = 0; i < numEvents[date]; i++) {
                dots.push(event); //add dots for as many events are on that day
            }
            markedData['dots'] = dots; //set the array of dots
            markedEvents[date] = markedData; //add markers to marked dates
        });
    };
    this.setState({markedDates: markedEvents});
}

dates 是从 API 传递的日期数组.

dates is an array of dates that is being passed from the API.

这应该为您输出一个带有每个日期标记的标记日期对象,并且如果您需要它,如果它在您的数组中出现多次,它将在一天中放置多个点.

This should output you a marked date object with the markings for each date, and also if you need it, it will put multiple dots on a day if it appears more than once in your array.

此外,我认为您的日期需要采用 ISO 日期格式 (YYYY-MM-DD),以便 react-native-calendars 标记日期.

Also, I believe your dates need to be in ISO date format (YYYY-MM-DD) for react-native-calendars to mark the dates.

我希望这个例子有帮助!

I hope this example helps!

这篇关于在 react-native-calendar 中动态标记日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 12:24