【发布时间】:2020-01-15 19:02:24
【问题描述】:
我正在尝试用时刻制作简单的日历。它第一次加载完美,但是当单击上一个或下一个我的 for 循环在渲染中运行两次时可能是问题
My project
https://stackblitz.com/edit/react-ts-itbzcd
public render() {
let day = this.props.date
for (let i = 0; i < 7; i++) {
this.days.push(
<Day key={day.toString()} date={day.date()} />
);
day = day.clone();
day.add(1, "day");
}
console.log(this.days)
return (
<tr key={this.days[0]}>
{this.days}
</tr>
);
}
完成Calendar组件:
import moment = require('moment');
import * as React from 'react'
import { DayNames, Week } from '.'
import styles from './Calendar.module.scss'
interface ICalendarProps {
}
interface ICalendarState {
dateObject: moment.Moment
showYearTable: boolean
}
export class Calendar extends React.Component<ICalendarProps, ICalendarState> {
constructor(props: ICalendarProps) {
super(props)
this.state = {
dateObject: moment(),
showYearTable: false
}
this.onNext = this.onNext.bind(this)
this.onPrev = this.onPrev.bind(this)
}
public render(): React.ReactElement<ICalendarProps> {
const datePicker =
<div className="datepicker-days">
<table className={styles.table}>
<thead>
<tr>
<th><span className="ms-Icon ms-Icon--ChevronLeft" title="Previous Month" onClick={this.onPrev}>Previous</span></th>
<th className={styles["picker-switch"]} data-action="pickerSwitch" colSpan={5} title="Select Month">
{this.month()}{" "} {this.year()}
</th>
<th><span className="ms-Icon ms-Icon--ChevronRight" title="Next Month" onClick={this.onNext}>Next</span></th>
</tr>
<tr>
<DayNames />
</tr>
</thead>
<tbody>
{this.renderWeeks()}
</tbody>
</table>
</div>
return (
<div className="datepicker">
{datePicker}
</div>
)
}
private month = () => {
return this.state.dateObject.format('MMMM')
}
private year = () => {
return this.state.dateObject.format("Y");
};
private onPrev = () => {
this.setState({
dateObject: this.state.dateObject.subtract(1, this.state.showYearTable === true ? "year" : "month")
});
};
private onNext = () => {
this.setState({
dateObject: this.state.dateObject.add(1, this.state.showYearTable === true ? "year" : "month")
});
};
private renderWeeks() {
let weeks = [];
let date = this.state.dateObject.clone().startOf("month").add("w").day("Sunday");
let done = false;
let count = 0;
let monthIndex = date.month();
while (!done) {
weeks.push(
<Week key={date.toString()} date={date.clone()} />
)
date.add(1, "w");
done = count++ > 2 && monthIndex !== date.month();
monthIndex = date.month();
}
return weeks
}
}
【问题讨论】:
标签: javascript reactjs typescript momentjs