import React,{Fragment} from 'react'; import moment from 'moment'; import { DatePicker,Input } from 'antd'; export interface Props { style?:any,//樣式 default?:string | moment.Moment,//默認值 form?:any,//表單 validationName?:string,//提交名稱,用於菜單提交獲取 submitString?:boolean,//提交類型爲字符串 format?:string,//字符串格式,用於默認值及提交值 } export interface State { date:moment.Moment | undefined,//選中的時間值,moment類型 dateVal:string,//選中的時間值,string類型 } class myDatePicker extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { date: typeof this.props.default === 'string'?moment(this.props.default,this.props.format):this.props.default, dateVal: typeof this.props.default === 'string'?this.props.default:(this.props.default!==undefined?this.props.default.format(this.props.format):''), }; } setData=(moment:moment.Moment | null,dateVal:string)=>{ let date:moment.Moment | undefined; if(moment === null){ date = undefined; }else{ date = moment; } this.setState({date,dateVal}); } render() { return ( <Fragment> <DatePicker value = {this.state.date} onChange={(moment:moment.Moment | null,dateVal:string)=> {this.setData(moment,dateVal)}} style={this.props.style} /> { this.props.form!== undefined && this.props.form.getFieldDecorator !== undefined? this.props.form.getFieldDecorator(this.props.validationName!== undefined ? this.props.validationName:'datePicker', { initialValue: this.props.submitString ? this.state.dateVal : this.state.date, })(<Input type="hidden"/>) :undefined } </Fragment> ); } } export default myDatePicker;
調用方式:
react