场景:
问题:
代码:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import DayPicker from 'react-day-picker';
import Helmet from 'react-helmet';
import 'react-day-picker/lib/style.css';
import moment from 'moment'
function getWeekDays(weekStart) {
const days = [weekStart];
for (let i = 1; i < 7; i += 1) {
days.push(
moment(weekStart)
.add(i, 'days')
.toDate()
);
}
return days;
}
function getWeekRange(date) {
return {
from: moment(date)
.startOf('week')
.toDate(),
to: moment(date)
.endOf('week')
.toDate(),
};
}
class App extends Component {
constructor(props) {
super(props);
this.handleDayClick = this.handleDayClick.bind(this);
this.state = {
selectedDay: null,
hoverRange: undefined,
selectedDays: [],
};
}
handleDayChange = date => {
this.setState({
selectedDays: getWeekDays(getWeekRange(date).from),
});
};
handleDayEnter = date => {
this.setState({
hoverRange: getWeekRange(date),
});
};
handleDayLeave = () => {
this.setState({
hoverRange: undefined,
});
};
handleWeekClick = (weekNumber, days, e) => {
this.setState({
selectedDays: days,
});
};
handleDayClick(day, { selected }) {
this.setState({
selectedDay: selected ? undefined : day,
});
}
render() {
const { hoverRange, selectedDays } = this.state;
const daysAreSelected = selectedDays.length > 0;
const modifiers = {
hoverRange,
selectedRange: daysAreSelected && {
from: selectedDays[0],
to: selectedDays[6],
},
hoverRangeStart: hoverRange && hoverRange.from,
hoverRangeEnd: hoverRange && hoverRange.to,
selectedRangeStart: daysAreSelected && selectedDays[0],
selectedRangeEnd: daysAreSelected && selectedDays[6],
};
return (
<div className="App">
<div>
<DayPicker
selectedDays={this.state.selectedDay}
onDayClick={this.handleDayClick}
/>
<p>
{this.state.selectedDay
? this.state.selectedDay.toLocaleDateString()
: 'Please select a day '}
</p>
</div>
<div className="SelectedWeekExample">
<DayPicker
selectedDays={selectedDays}
showWeekNumbers
showOutsideDays
modifiers={modifiers}
onDayClick={this.handleDayChange}
onDayMouseEnter={this.handleDayEnter}
onDayMouseLeave={this.handleDayLeave}
onWeekClick={this.handleWeekClick}
/>
{selectedDays.length === 7 && (
<div>
{moment(selectedDays[0]).format('LL')} –{' '}
{moment(selectedDays[6]).format('LL')}
</div>
)}
</div>
</div>
);
}
}
export default App;
我愿意接受所有建议,请提出建议。
谢谢!
答案 0 :(得分:0)
好吧,我明白了。我用过这样的东西,而且效果很好。
handleDayChange = date => {
this.setState({
selectedDays: getWeekDays(getWeekRange(date).from),
clicked: this.state.clicked +1
})
if((this.state.clicked ==1)) {
this.setState({
clicked: 0,
selectedDay:date
})
if(this.state.selectedDay){
this.setState({selectedDays:date})
}
}
};