{day}
);
}
// 这里我们简单处理,不添加额外的空白格子来补全一周
// 在实际项目中,你可能需要计算并添加这些空白格子
return days;
};
// 切换月份
const handlePrevMonth = () => {
if (month === 1) {
setYear(year - 1);
setMonth(12);
} else {
setMonth(month - 1);
}
};
const handleNextMonth = () => {
if (month === 12) {
setYear(year + 1);
setMonth(1);
} else {
setMonth(month + 1);
}
};
return (
{`${year}-${month.toString().padStart(2, '0')}`}
);
};
export default Calendar;
```
### 第三步:添加样式
为了提升用户体验,我们需要给日历添加一些基本的CSS样式。你可以在项目的`src/App.css`或创建一个新的`Calendar.css`文件,并将以下样式添加进去。
```css
/* 假设这是添加在App.css中的样式 */
.calendar {
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
}
.calendar button {
padding: 5px 10px;
cursor: pointer;
}
.weekdays, .days {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 5px;
}
.weekday-cell, .day-cell {
padding: 10px;
border: 1px solid #ccc;
text-align: center;
}
.day-cell.empty {
background-color: #f0f0f0;
}
```
### 第四步:集成到App中
现在,你已经有了一个基本的日历组件,接下来需要将它集成到你的React应用的`App.js`文件中。
```jsx
import React from 'react';
import './App.css';
import Calendar from './Calendar'; // 假设Calendar.js和App.js在同一目录下
function App() {
return (
{['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((day, index) => (
{day}
))}
{renderDays()}