import React from "react";
import { DatePicker, Input } from "antd";
import styles from "./index.scss";
import moment from "moment";
class MonthPick extends React.Component {
constructor(props) {
super(props);
this.state = {
inputText: "",
value: "",
};
}
handleOpenChange = (open) => {
const { value } = this.props;
if (open) {
this.setState(
{
inputText: value ? moment(value).format("YYYY-MM") : "",
},
() => {
setTimeout(() => {
document.getElementById("inputBox").focus();
}, 0);
}
);
}
};
// 月份发生变化传值出去
handleChange = (changedValue) => {
const { onChange } = this.props;
let data = changedValue;
this.setState({ inputText: moment(changedValue).format("YYYY-MM") });
const dataStr = changedValue ? moment(changedValue).format("YYYY-MM") : "";
if (onChange) {
onChange(data, dataStr);
}
};
inputTextChangeFn = (e) => {
const { disabledDate } = this.props;
this.setState({
inputText: e.target.value,
});
if (!e.target.value) {
this.handleChange("");
this.setState({ inputText: "" });
return;
}
let changedValue = moment(e.target.value);
// 数据格式是否正确
if (/^[1-9]\d{3}-(0[1-9]|1[0-2])$/.test(e.target.value)) {
// 是否有不可选数据
if (disabledDate) {
this.isDisabledDateFn(changedValue);
} else {
this.handleChange(changedValue);
}
}
};
isDisabledDateFn = (val) => {
const { disabledDate } = this.props;
if (!disabledDate(val)) {
this.handleChange(val);
}
};
// 处理人员详情页面点击月份组件按钮有时候没有反应的bug
changeYearFn = (e) => {
if (e.target.getAttribute("class") == "ant-calendar-month-panel-next-year-btn") {
e.stopPropagation();
}
if (e.target.getAttribute("class") == "ant-calendar-month-panel-prev-year-btn") {
e.stopPropagation();
}
if (e.target.getAttribute("class") == "ant-calendar-year-panel-year") {
e.stopPropagation();
}
if (e.target.getAttribute("class") == "ant-calendar-decade-panel-decade") {
e.stopPropagation();
}
if (e.target.getAttribute("class") == "ant-calendar-picker-clear") {
e.stopPropagation();
}
};
render() {
const { inputText } = this.state;
const { value, placeholder } = this.props;
return (
<div className={styles.monthBox} id="monthBox" onClick={(e) => this.changeYearFn(e)}>
<DatePicker.MonthPicker
{...this.props}
dropdownClassName="monthPickBox"
renderExtraFooter={() => (
<Input
id="inputBox"
style={{ width: "280px", height: "32px", border: "none" }}
value={inputText}
onChange={this.inputTextChangeFn}
placeholder={placeholder ? placeholder : "请选择日期"}
/>
)}
// 解决上下滚动月份弹窗没有跟着移动的bug
// getCalendarContainer={triggerNode => {
// console.log(triggerNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode);
// if(moreLevel) {
// return triggerNode.parentNode
// }
// return triggerNode.parentNode
// }}
format="YYYY-MM"
onOpenChange={this.handleOpenChange}
value={value ? moment(value) : undefined}
onChange={this.handleChange}
/>
</div>
);
}
}
export default MonthPick;
效果
image.png
网友评论