我创建了一个React日历组件:
我试图遍历一系列事件并在相应的日期展示该事件。
这是事件数组:
const events = [
{
title: 'Today',
start: new Date()
}
]
这是呈现单元格的代码:
const Cells = ({currentMonth, events}) => {
const monthStart = dateFns.startOfMonth(currentMonth);
const monthEnd = dateFns.endOfMonth(monthStart);
const startDate = dateFns.startOfWeek(monthStart);
const endDate = dateFns.endOfWeek(monthEnd);
const dateFormat = "D";
const rows = [];
let days = [];
let day = startDate;
let formattedDate = "";
while (day <= endDate) {
for (let i = 0; i < 7; i++) {
formattedDate = dateFns.format(day, dateFormat);
const event = events.filter((event, i) => dateFns.format(event.start, 'MM/DD/YYYY') === dateFns.format(day, 'MM/DD/YYYY'))
console.log(event)
days.push(
<Cell today={dateFns.isSameDay(day, new Date())} key={day}>
<span>{formattedDate}</span>
<div>Event</div>
</Cell>
);
day = dateFns.addDays(day, 1);
}
rows.push(
<Row key={day}>
{days}
</Row>
);
days = [];
}
return <DateWrapper>{rows}</DateWrapper>;
}
在for
循环中注意此过滤器:
const event = events.filter((event, i) => dateFns.format(event.start,'MM/DD/YYYY') === dateFns.format(day,'MM/DD/YYYY'))
console.log(event)
一个数组按计划返回事件:
[{…}]
0: start: Fri Apr 12 2019 18:43:50 GMT-0400 (Eastern Daylight Time) {}
title: "Today"
所以我的问题是,在此部分展示事件的正确方法是什么?将“事件”一词替换为实际的事件标题:
days.push(
<Cell today={dateFns.isSameDay(day, new Date())} key={day}>
<span>{formattedDate}</span>
<div>Event</div>
</Cell>
);
答案 0 :(得分:0)
就像我最初想的那样,这有点复杂。我想你应该做类似的事情
const eventsArray = events.reduce(
(a, b) => {
(a[dateFns.format(b.start, 'MM/DD/YYYY')] = a[dateFns.format(b.start, 'MM/DD/YYYY')] || []).push(b);
return a
},
{})
然后,您将按日期对事件进行分组。最后,您可以将它们映射到Cell
组件
let days
days = Object.keys(eventsArray).map((day, index) =>
<Cell today={dateFns.isSameDay(day, new Date())} key={day}>
<span>{day}</span>
{eventsArray[day].map(event => <div>{event.title}</div>)}
</Cell>)
);