react+ts封装AntdUI的日期选择框之月份选择器DatePicker.month


需求:由于在项目开发中,当需要使用该组件时都需要对该组件进行大量的代码输出,为了方便代码统一管理,减少冗余代码,所以将此组件进行二次封装。

其他成员在使用中只需将自己的设置通过对应的参数传递到该组件,在执行选中操作后直接将返回值回传给调用的父组件即可。

技术涉及:react+ts+antd

代码如下:

parent.tsx

import React from 'react';
import MonthPicker from '../components/DatePicker/children';
import moment from 'moment';

class FormsView extends React.Component {
    constructor(props: {}) {
        super(props)
        this.state = {
        }
    }
    getSelectMonth(data: any) {
        console.log('获取选中的月份', data);
    }
    disabledDate1(current:any) {
    // 设置不可选的日期
return current && current > moment().endOf('day'); } render() { return <div className="parent"> <MonthPicker data={new Date()} getSelectMonth={this.getSelectMonth.bind(this)} setDisableDate={this.disabledDate1.bind(this)}></MonthPicker> </div> } } export default FormsView

封装的月份选择器  children.tsximport React from 'react';import { DatePicker } from 'antd';import moment from 'moment';


interface Props {
    data: Date                  // value
    getSelectMonth?: any        // 回调函数
    setClassName?: string       // 设置面板样式
    setDateChange?: number      // 月份显示形式 0默认(1月)1(一月)
    setDisableDate?: any        // 不可选择的月份    
    setMonthClassName?: string  // 下拉面板样式
}
class Children extends React.Component<Props, any> {
    constructor(props) {
        super(props)
        this.state = {
            monthFormat: 'YYYY/MM',
  
       emunObject: {
          1: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],
          2: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        },
            popupStyle: {},             monthData: this.props.data || new Date(),
 dateType: this.props.setDateChange || 0, dateBoxClassName: this.props.setClassName, dateMonthClassName: this.props.setMonthClassName || 'default-picker', dateDisableDate: this.props.setDisableDate } } handleChange(value: any, option: any) { this.props.getSelectMonth(option); } render() { return <div className="date-picker">
            <DatePicker picker="month" placeholder="请选择" size="middle" className={this.state.dateBoxClassName} monthCellRender={(date, locale)=>{ return <div className={this.state.dateMonthClassName}> { !this.state.dateType ? (date.month()+1)+locale.month 
                :this.state.emunObject[this.state.dateType][date.month()]}
               </div>
 }} popupStyle={this.state.popupStyle} defaultValue={moment(this.state.monthData, this.state.monthFormat)} format={this.state.monthFormat} disabledDate={this.state.dateDisableDate} onChange={this.handleChange.bind(this)} /> </div>  } } export default Children
interface Props中是定义的接口属性,其中data是接收当前默认需要显示的值的,是必须的参数;其他带有问号❓的属性是可选择的,既非必传,根据需要设置。
因为下拉的面板展示的文本是数字+月,因此需要展示为中文月份的就需要用到转换属性。

 

小伙伴们可以直接复制使用,也可以在此基础上操作更多的自定义,反正都是以需求为主的啦。当然,有疑问的话也可以留言一起讨论哦!!!(*^__^*)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM