Ant Design中DatePicker设置mode="year"无法获取value
问题描述
<DatePicker
placeholder="请选择年份"
mode="year"
onChange={this.onChange}
/>
使用上边代码,界面呈现出只有年份的选择器。但是,不管你怎么点击按钮选择年份都不会起作用, onChange 事件根本不会触发,所以value获取不了!
解决办法
查看文档:
1、onOpenChange 方法,是这样描述的:弹出日历和关闭日历的回调, 可以通过 onOpenChange 方法判断当前的操作是要面板关闭还是打开,来控制面板的显隐。
2、onPanelChange方法,是这样描述的:日历面板切换的回调,可以通过这个方法获取value值
3、onChange方法,可以通过onChange方法控制点击清除图标时清除数据
1、不使用form
import React, {Component} from 'react';
import {DatePicker} from 'antd';
export default class extends Component {
state = {
datePickerOpen: false,
datePickerData: null
}
render() {
const {datePickerOpen, datePickerData} = this.state
return (
<div>
<DatePicker
value={datePickerData}
open={datePickerOpen}
mode="year"
placeholder="请选择年份"
format="YYYY"
onOpenChange={(status) => {
if (status) {
this.setState({datePickerOpen: true})
} else {
this.setState({datePickerOpen: false})
}
}}
onPanelChange={(v) => {
console.log(v)
this.setState({
datePickerData: v,
datePickerOpen: false
})
}}
onChange={() => {
this.setState({datePickerData: null})
}}
/>
</div>
)
}
}
2、使用form
import React, {Component} from 'react';
import {DatePicker, Form} from 'antd';
const FormItem = Form.Item;
export default class extends Component {
state = {
datePickerOpen: false,
datePickerData: null
}
//日期组件显示控制
datePickerOpenChange = status => {
if (status) {
console.log(status)
this.setState({datePickerOpen: true})
} else {
this.setState({datePickerOpen: false})
}
}
//选择年后触发
dataPickerPanelChange = v => {
console.log(v)
this.props.form.setFieldsValue({datePickerData: v})
this.setState({
datePickerOpen: false
})
}
//点击清除按钮触发
dataPickerChange = () => {
this.props.form.setFieldsValue({datePickerData: null})
}
render() {
const {datePickerOpen, datePickerData} = this.state
const {getFieldDecorator} = this.props.form;
return (
<div>
<Form
layout="horizontal"
style={{paddingBottom: 18}}
>
<FormItem>
{getFieldDecorator("datePickerData", {
initialValue: datePickerData,
rules: [{required: true, message: '请选择真题年份'}]
})(
<DatePicker
open={datePickerOpen}
mode="year"
placeholder="请选择年份"
format="YYYY"
onOpenChange={(status) => this.datePickerOpenChange(status)}
onPanelChange={(v) => this.dataPickerPanelChange(v)}
onChange={() => this.dataPickerChange}
/>
)}
</FormItem>
</Form>
</div>
)
}
}
结果处理
选完年之后得到的值是这样的
所以,可以通过format
获取到年数据:
datePickerData.format('YYYY')
将年转为日期
import moment from 'moment';
datePickerData = moment(2017, 'YYYY')