CSS grid, Day.js : 如何创建显示当前周日期的日历?

CSS grid, Day.js : How do I create a calendar that shows the current week's dates?

在一个 React 组件中,我想创建一个网格日历来显示当前一周的日期。因此,以本周为例,它需要看起来像这样:

Monday          | Tuesday         |Wednesday       |        
October 5th 2020| October 6th 2020|October 7th 2020|

我试过 day.js 来尝试解决这个问题,但事实证明这很棘手。这是我在 codesanbox 中的尝试:

https://codesandbox.io/s/sleepy-rgb-me4s3?file=/src/App.js

关于如何处理这个问题有什么建议吗?我不确定如何将每个网格的开始设置为给定一周的星期一 - 一旦我这样做了,我就可以弄清楚其他日子的逻辑。

代码如下:

Grid component

import React from "react";
import "./styles.css";
import dayjs from 'dayjs'

export default App = () => {

  let now = dayjs()
  let currentDay = (now.format("dddd, MMMM D YYYY"))

  let d = now.add('1', 'day')
  let nextDay = (d.format("dddd, MMMM D YYYY"))
  
  return(
    <div className = 'grid-container'>
      <div className = 'grid-item'>{currentDay}</div>
      <div className = 'grid-item'>{nextDay}</div>
      <div className = 'grid-item'></div>
      <div className = 'grid-item'></div>
      <div className = 'grid-item'></div>
      <div className = 'grid-item'></div>
      <div className = 'grid-item'></div>
    </div>
  )
}

styles.css

.grid-container {
  display: grid;
  grid-template-rows: repeat(3, 100px);
  grid-row-gap:1px;
  grid-template-columns: 100px 100px 100px;
  grid-column-gap: 1px;
}

.grid-item {
  background-color: blue;
  color:white;
}

您可以使用startOf('week')获取当前周的第一天,然后构造一个包含该周所有7天的数组来渲染它:

export default () => {
  const startOfWeek = dayjs().startOf("week");

  const weekdays = new Array(7).fill(startOfWeek).map(
    (day, idx) => day.add(idx, "day").format("dddd, MMMM D YYYY")
  );

  return (
    <div className="grid-container">
      {weekdays.map((day) => (
        <div key={day} className="grid-item">
          {day}
        </div>
      ))}
    </div>
  );
};

一周的开始时间可能因地区而异。您可以通过 setting it in the locale:

将一周的开始设置为星期一
import en from "dayjs/locale/en";

dayjs.locale({
  ...en,
  weekStart: 1
});

如果您不想修改语言环境,您也可以使用 day(1) 来获取本周的星期一:

const startOfWeek = dayjs().day(1); // will be the monday of the current week with the default locale