答案 0 :(得分:3)
而不是使用Fields
组件创建自定义字段。这是一般的想法:
class DOBSelects extends React.Component {
constructor(props) {
super(props);
this.state = this.buildState(props.input.value)
}
componentWillReceiveProps(props) {
if(props.input.value !== this.props.input.value) {
this.setState(this.buildState(props.input.value));
}
}
buildState(value) {
return value ? {
date: value.getDate(),
month: value.getMonth() + 1, year:
value.getFullYear()
} : {
date: '',
month: '',
year: ''
}
}
update(state) {
this.setState(state);
const { date, month, year } = { ...this.state, ...state };
const { onChange, value } = this.props.input;
if(date && month && year) {
onChange(new Date(year, month - 1, date));
} else if(value) {
onChange(null);
}
}
render () {
const { label, input: { name } } = this.props;
const { date, month, year } = this.state
const thisYear = new Date().getFullYear();
return (
<div>
<label htmlFor={name + '-day'}>
{label}
</label>
<select onChange={e => { this.update({ date: e.target.value }); }} value={date} name={name + '-day'}>
<option />
{getOptions(1, 31)}
</select>
<select onChange={e => this.update({ month: e.target.value })} value={month} name={name + '-month'}>
<option />
{getOptions(1, 12)}
</select>
<select onChange={e => this.update({ year: e.target.value })} value={year} name={name + '-year'}>
<option />
{getOptions(thisYear - 20, thisYear)}
</select>
</div>
);
};
}
function getOptions(start, end) {
const options = [];
for(let i = start; i <= end; i++) {
options.push(<option key={i}>{i}</option>)
}
return options;
}
更简单的解决方案是使用类似react-datepicker的内容。