// 父组件
import SalesCard from './components/SalesCard';
import { getTimeDistance } from './utils/utils';
import styles from './style.less';
const Analysis = () => {
const [rangePickerValue, setRangePickerValue] = useState(getTimeDistance('year'));
console.log(rangePickerValue) // 这个就是要获取的Pickervalue值
// 封装一个方法 ,点击的时候更新type
const selectDate = (type) => {
setRangePickerValue(getTimeDistance(type));
};
// 接收子组件传过来的,当组将改变的时候获取值
const handleRangePickerChange = (value) => {
setRangePickerValue(value);
};
const isActive = (type) => {
if (!rangePickerValue) {
return '';
}
const value = getTimeDistance(type);
if (!value) {
return '';
}
if (!rangePickerValue[0] || !rangePickerValue[1]) {
return '';
}
if (
rangePickerValue[0].isSame(value[0], 'day') &&
rangePickerValue[1].isSame(value[1], 'day')
) {
return styles.currentDate;
}
return '';
};
return (
<>
<SalesCard
rangePickerValue={rangePickerValue}
isActive={isActive}
handleRangePickerChange={handleRangePickerChange}
selectDate={selectDate}
/>
</>
);
};
export default Analysis;
// 子组件
import { DatePicker } from 'antd';
import styles from '../style.less';
const { RangePicker } = DatePicker;
const SalesCard = ({
rangePickerValue,
isActive,
handleRangePickerChange, //这是子传父方法
selectDate,
}) => {
return (
<div className={styles.salesCard}>
<div className={styles.salesExtraWrap}>
<div className={styles.salesExtra}>
<a className={isActive('today')} onClick={() => selectDate('today')}>
今日
</a>
<a className={isActive('week')} onClick={() => selectDate('week')}>
本周
</a>
<a className={isActive('month')} onClick={() => selectDate('month')}>
本月
</a>
<a className={isActive('year')} onClick={() => selectDate('year')}>
本年
</a>
</div>
<RangePicker
value={rangePickerValue}
onChange={handleRangePickerChange}
style={{
width: 256,
}}
/>
</div>
</div>
)
}
export default SalesCard;
until.js里面type封装
import moment from 'moment';
export function fixedZero(val) {
return val * 1 < 10 ? `0${val}` : val;
}
export function getTimeDistance(type) {
const now = new Date();
const oneDay = 1000 * 60 * 60 * 24;
if (type === 'today') {
now.setHours(0);
now.setMinutes(0);
now.setSeconds(0);
return [moment(now), moment(now.getTime() + (oneDay - 1000))];
}
if (type === 'week') {
let day = now.getDay();
now.setHours(0);
now.setMinutes(0);
now.setSeconds(0);
if (day === 0) {
day = 6;
} else {
day -= 1;
}
const beginTime = now.getTime() - day * oneDay;
return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
}
const year = now.getFullYear();
if (type === 'month') {
const month = now.getMonth();
const nextDate = moment(now).add(1, 'months');
const nextYear = nextDate.year();
const nextMonth = nextDate.month();
return [
moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000),
];
}
return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
}