用react中创建组件的方法生成一个日历和待办事项表
时间: 2023-06-12 12:04:18 浏览: 223
好的,下面是一个简单的日历和待办事项表的 React 组件的实现:
```javascript
import React, { useState } from 'react';
const Calendar = () => {
const [date, setDate] = useState(new Date());
const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const monthsOfYear = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
const month = date.getMonth();
const year = date.getFullYear();
const firstDayOfMonth = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
const prevMonth = () => setDate(new Date(year, month - 1, 1));
const nextMonth = () => setDate(new Date(year, month + 1, 1));
return (
<div className="calendar">
<div className="calendar-header">
<button onClick={prevMonth}><</button>
<h2>{monthsOfYear[month]} {year}</h2>
<button onClick={nextMonth}>></button>
</div>
<table className="calendar-table">
<thead>
<tr>
{daysOfWeek.map(day => (
<th key={day}>{day}</th>
))}
</tr>
</thead>
<tbody>
{[...Array(Math.ceil((firstDayOfMonth + daysInMonth) / 7)).keys()].map(week => (
<tr key={week}>
{[...Array(7).keys()].map(day => {
const dateOfMonth = week * 7 + day + 1 - firstDayOfMonth;
return (
<td key={day}>
{dateOfMonth > 0 && dateOfMonth <= daysInMonth && dateOfMonth}
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
);
};
const TodoList = () => {
const [todos, setTodos] = useState([]);
const [inputValue, setInputValue] = useState('');
const handleInput = e => setInputValue(e.target.value);
const handleSubmit = e => {
e.preventDefault();
if (inputValue.trim() !== '') {
setTodos([...todos, inputValue.trim()]);
setInputValue('');
}
};
const handleDelete = i => {
setTodos([...todos.slice(0, i), ...todos.slice(i + 1)]);
};
return (
<div className="todo-list">
<form onSubmit={handleSubmit}>
<input type="text" value={inputValue} onChange={handleInput} />
<button type="submit">Add</button>
</form>
<ul>
{todos.map((todo, i) => (
<li key={i}>
{todo}
<button onClick={() => handleDelete(i)}>×</button>
</li>
))}
</ul>
</div>
);
};
const App = () => (
<div>
<Calendar />
<TodoList />
</div>
);
export default App;
```
这个组件中包含了一个简单的日历和一个待办事项列表,你可以在 `Calendar` 组件中修改一些细节,例如添加一些交互性和样式来更好地适应你的需求。
阅读全文