繁体   English   中英

如何在反应日期中添加一年的选择?

[英]How to add a select for a year in react-dates?

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

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

  1. npm install react-dates@latest
  2. 由于重大更改,您可能需要根据docs更新一些内容(对我而言,大多数情况下是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} /> } 

为了稍微调整@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循环以打印出您需要的年份。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM