ReactJs。水平日历设定日期

时间:2019-02-05 11:09:20

标签: javascript reactjs

我正在使用库MomentJS。 函数renderDays呈现一个天数组。

我面临的问题是,我只需要在当前日期前5天和5天后显示。

renderDays() {
    const {classes} = this.props;
    const getDaysArrayByMonth = () => {
      let renderAllMonthDays = moment().daysInMonth();
      let listOfDays = [];
      while ( renderAllMonthDays - 17 ) {
        const current = moment().date(renderAllMonthDays);
        listOfDays.push(current);
        renderAllMonthDays--;
      }
      return listOfDays.reverse();
    };
    const days = getDaysArrayByMonth();
    return (
      <div className={classes.daysRow}>
        {_.map(days, (days, index) => (
          <Button className={classes.dayItem} key={index}>
            <div className={classes.dayItemText}>
              <span> {days.format("DD")}</span>
              <span> {days.format("ddd")}</span>
            </div>
          </Button>
        ))}
      </div>
    )
  };

1 个答案:

答案 0 :(得分:0)

您可以使用for()循环和moment.add()函数来做到这一点:

let listOfDays = [];
const today = moment();

//start at -5, adding a negative number of days is the same as subtracting
for (let dayDifference = -5; dayDifference <=5; dayDifference++) {

    //make sure we take a copy of the current day, or .add() will change it
    const newDay = moment(today).add(dayDifference, 'days');

    listOfDays.push(newDay);
}

如果仅包含午夜的数组很重要,则可以

 const today = moment().startOf('day');

相反,但是出于您的目的,这可能并不重要。