0

我想强调从当前日期开始的接下来的两周。我正在使用react-datepicker模块。我使用了以下代码:

var currentDate = new Date();
var numberOfDaysToAdd = 13;
const daysHighlighted = new Array(numberOfDaysToAdd).fill(currentDate);

return (
    <DatePicker
        selected={this.state.startDate}
        onChange={this.handleChange}
        highlightDates={[{
            "react-datepicker__day--highlighted": daysHighlighted.map((day, index) => {
                day.setDate(day.getDate() + index)
                return new Date(day)
            })
        }]}
    />
)

这给了我意想不到的结果。

我只想强调下两周,包括当前日期。

4

1 回答 1

0

fillDate函数用相同的实例填充数组。因此,每当您使用 更新日期时setDate,它都会更改该数组其他日期的值。因为它们都指向同一个对象。

你可以尝试这样的事情:

new Array(numberOfDaysToAdd).fill().map((_, i) => {   // fills the array with `undefined`
  const d = new Date();                               // create a new Date instance
  d.setDate(d.getDate() + i);                         // update only that instance
  return d;                                           // return the updated date
})

现在您可以将此数组用作react-datepicker__day--highlighted键的值:

<DatePicker
    selected={this.state.startDate}
    onChange={this.handleChange}
    highlightDates={[{
        "react-datepicker__day--highlighted": new Array(numberOfDaysToAdd).fill().map((_, i) => {  
          const d = new Date();
          d.setDate(d.getDate() + i);
          return d;
      })
    }]}
/>
于 2019-02-21T19:50:51.683 回答