3

在我到达正确的年份之前向右滑动几个月是很痛苦的react-dates,是否可以为年份/月份添加一些选择

4

2 回答 2

15

是的,因为版本react-dates@17.0.0是可能的!(相关的拉取请求)。

  1. npm install react-dates@latest
  2. 由于重大更改(对我来说主要是 css),您可能需要根据文档更新一些内容。
  3. 然后利用新引入的 renderMonthElement道具来编写您的自定义月份和年份选择器,例如:

    import React from 'react';
    import moment from 'moment';
    import { SingleDatePicker } from 'react-dates';
    
    class Main extends React.Component {
      state = {
        date: moment(),
        focused: true
      }
    
      renderMonthElement = ({ month, onMonthSelect, onYearSelect }) =>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <div>
            <select
              value={month.month()}
              onChange={(e) => onMonthSelect(month, e.target.value)}
            >
              {moment.months().map((label, value) => (
                <option value={value}>{label}</option>
              ))}
            </select>
          </div>
          <div>
            <select value={month.year()} onChange={(e) => onYearSelect(month, e.target.value)}>
              <option value={moment().year() - 1}>Last year</option>
              <option value={moment().year()}>{moment().year()}</option>
              <option value={moment().year() + 1}>Next year</option>
            </select>
          </div>
        </div>
    
      render = () =>
        <SingleDatePicker
          date={this.state.date}
          onDateChange={(date) => this.setState({ date })}
    
          focused={this.state.focused}
          onFocusChange={({ focused }) => this.setState({ focused })}
    
          renderMonthElement={this.renderMonthElement}
        />
    }
    
于 2018-09-16T19:46:57.000 回答
5

为了稍微调整@lakesare 对于那些想要列出生日的人的答案,比如过去 100 年的生日,这里有一个代码片段:

renderMonthElement = ({ month, onMonthSelect, onYearSelect }) => {
    let i
    let years = []
    for(i = moment().year(); i >= moment().year() - 100; i--) {
        years.push(<option value={i} key={`year-${i}`}>{i}</option>)
    }
    return (
        <div style={{ display: "flex", justifyContent: "center" }}>
            <div>
                <select value={month.month()} onChange={e => onMonthSelect(month, e.target.value)}>
                    {moment.months().map((label, value) => (
                        <option value={value} key={value}>{label}</option>
                    ))}
                </select>
            </div>
            <div>
                <select value={month.year()} onChange={e => onYearSelect(month, e.target.value)}>
                    {years}
                </select>
            </div>
        </div>
    )
}

render() {
    return (
        <SingleDatePicker
            ...
            renderMonthElement={this.renderMonthElement}
        />
    )
}

修改第 4 行的 for 循环以打印出您需要的任何年份。

于 2019-08-27T02:18:39.083 回答