向右滑动月份直到我用react-dates
到达正确的年份很痛苦,是否可以为年/月添加一些选择?
是的,这是可能的,因为版本反应-dates@17.0.0!(相关的拉取请求(。
npm install react-dates@latest
- 您可能需要更新 根据文档的几件事,因为重大更改 (对我来说主要是 CSS(。
-
然后利用新引入的
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} /> }
为了稍微调整那些想要列出过去 100 年生日的人的@lakesare答案,这里有一个代码片段:
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 循环以打印出您需要的任何年份。