需求:由於在項目開發中,當需要使用該組件時都需要對該組件進行大量的代碼輸出,為了方便代碼統一管理,減少冗余代碼,所以將此組件進行二次封裝。
其他成員在使用中只需將自己的設置通過對應的參數傳遞到該組件,在執行選中操作后直接將返回值回傳給調用的父組件即可。
技術涉及: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是接收當前默認需要顯示的值的,是必須的參數;其他帶有問號❓的屬性是可選擇的,既非必傳,根據需要設置。
因為下拉的面板展示的文本是數字+月,因此需要展示為中文月份的就需要用到轉換屬性。
小伙伴們可以直接復制使用,也可以在此基礎上操作更多的自定義,反正都是以需求為主的啦。當然,有疑問的話也可以留言一起討論哦!!!(*^__^*)