发布时间:2024-11-02 09:01
需求:
- 显示所有todo列表
- 输入文本,点击按钮显示到列表的首位,并清除输入的文本
App.jsx
export default class App extends Component {
// 初始化状态
state = {
todos: [
{ id: \'001\', name: \'吃饭\', done: true },
{ id: \'002\', name: \'睡觉\', done: true },
{ id: \'003\', name: \'打代码\', done: false },
{ id: \'004\', name: \'逛街\', done: true },
]
};
render() {
return (
<div className=\"todo-container\">
<div className=\"todo-wrap\">
<Header />
{/* 在父组件App中初始化状态,然后通过props传给子组件List */}
<List todos={this.state.todos} />
<Footer />
</div>
</div>
);
}
}
子组件List接收父组件传过来的todos,遍历todos,将拿到的每一项的属性传给Item组件。
List.jsx
export default class List extends Component {
render() {
// 接收父组件传过来的todos
const { todos } = this.props
return (
<ul className=\"todo-main\">
{/* 遍历todos */}
{
// todo: todos里的每一项
todos.map((todo) => {
return <Item key={todo.id} {...todo} />
// {...todo} ==> id={todo.id} name={todo.name} done={this.done}
// {...todo}:批量传递对象
})
}
</ul>
);
}
}
子组件Item接收List传过来的信息,实现是否选中以及动态更新名称的功能
Item.jsx
export default class Item extends Component {
render() {
const { id, name, done } = this.props
return (
<li>
<label>
{/* defaultChecked:只在初次渲染时生效,更新时不受控制 */}
<input type=\"checkbox\" defaultChecked={done} />
<span>{name}</span>
</label>
<button className=\"btn btn-danger\" style={{ display: \"none\" }}>删除</button>
</li>
);
}
}
App.jsx
// addTodo用于添加一个todo,接收的参数是todo对象
addTodo = (todoObj) => {
// 获取原todos
const { todos } = this.state
// 追加一个todo
const newTodos = [todoObj, ...todos]
this.setState({ todos: newTodos })
}
render() {
return (
<div className=\"todo-container\">
<div className=\"todo-wrap\">
{/* 子传父:父组件给子组件传递一个自定义方法,通过props传递这个方法,
子组件通过调用这个方法给父组件传递数据 */}
<Header addTodo={this.addTodo} />
{/* 父传子:在父组件App中初始化状态,然后通过props传给子组件List */}
<List todos={this.state.todos} />
<Footer />
</div>
</div>
);
}
Header.jsx
handleKeyUp = (event) => {
// console.log(event.key, event.keyCode)
// 解构赋值获取 keyCode, target
const { key, target } = event
// 判断是否是回车按键
if (key !== \'Enter\') return
// 添加的todo名字不能为空
if (target.value.trim() === \'\') {
alert(\'输入不能为空\')
return
}
// 准备好一个todo对象
const todoObj = { id: nanoid(), name: target.value, done: false }
// 将todoObj传递给App
this.props.addTodo(todoObj)
// 清空输入
target.value = \'\'
}
还有实现鼠标移入高亮的效果;实现勾选和取消勾选每一项时,更新状态的效果;删除一个选项的效果;全选和全不选的效果;清除已完成的任务的效果等等,就不一一详细解释了。
此Demo整体的代码如下:
index.js:
import React from \'react\'
import ReactDOM from \'react-dom/client\';
import App from \'./App\'
const root = ReactDOM.createRoot(document.getElementById(\'root\'));
root.render(
<React.StrictMode>
{/* 检查App组件以及子组件里的一些代码是否有不合理的地方 */}
<App />
</React.StrictMode>
);
App.jsx:
import React, { Component } from \'react\';
import Header from \'./components/Header\'
import Footer from \'./components/Footer\'
import List from \'./components/List\';
import \'./App.css\'
export default class App extends Component {
// 状态在哪里,操作状态的方法就在哪里
// 初始化状态
state = {
todos: [
{ id: \'001\', name: \'吃饭\', done: true },
{ id: \'002\', name: \'睡觉\', done: true },
{ id: \'003\', name: \'打代码\', done: false },
{ id: \'004\', name: \'逛街\', done: true },
]
};
// addTodo用于添加一个todo,接收的参数是todo对象
addTodo = (todoObj) => {
// 获取原todos
const { todos } = this.state
// 追加一个todo
const newTodos = [todoObj, ...todos]
this.setState({ todos: newTodos })
}
// updateTodo用于更新一个todo对象
updateTodo = (id, done) => {
// 获取状态中的todos
const { todos } = this.state
// 匹配处理数据,遍历整个todos,将某一个匹配上的id的done更改
const newTodos = todos.map((todoObj) => {
// ...todoObj:复制一份todoObj,将done值改成传过来的done值
if (todoObj.id === id) return { ...todoObj, done: done }
else return todoObj
})
this.setState({ todos: newTodos })
}
// deleteTodo用于删除一个todo对象
deleteTodo = (id) => {
// 获取原来的todos
const { todos } = this.state
// 删除指定id的todo对象
const newTodos = todos.filter((todoObj) => {
return todoObj.id !== id
})
// 更新状态
this.setState({ todos: newTodos })
}
// checkAllTodo用于全选
checkAllTodo = (done) => {
// 获取原来的todos
const { todos } = this.state
// 加工数据
const newTodos = todos.map((todoObj) => {
return { ...todoObj, done: done }
})
// 更新状态
this.setState({ todos: newTodos })
}
// clearAllDone用于清除所有已完成的
clearAllDone = () => {
// 获取原来的todos
const { todos } = this.state
// 过滤数据
const newTodos = todos.filter((todoObj) => {
return todoObj.done === false
// return !todoObj.done
})
// 更新状态
this.setState({ todos: newTodos })
}
render() {
return (
<div className=\"todo-container\">
<div className=\"todo-wrap\">
{/* 子传父:父组件给子组件传递一个自定义方法,通过props传递这个方法,子组件通过调用这个方法给父组件传递数据 */}
<Header addTodo={this.addTodo} />
{/* 父传子:在父组件App中初始化状态,然后通过props传给子组件List */}
{/* 先将updateTodo传给List组件,List反手传给Item */}
<List todos={this.state.todos} updateTodo={this.updateTodo} deleteTodo={this.deleteTodo} />
<Footer todos={this.state.todos} checkAllTodo={this.checkAllTodo} clearAllDone={this.clearAllDone} />
</div>
</div>
);
}
}
App.css:
/*base*/
body {
background: #fff;
}
.btn {
display: inline-block;
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
text-align: center;
vertical-align: middle;
cursor: pointer;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
border-radius: 4px;
}
.btn-danger {
color: #fff;
background-color: #da4f49;
border: 1px solid #bd362f;
}
.btn-danger:hover {
color: #fff;
background-color: #bd362f;
}
.btn:focus {
outline: none;
}
.todo-container {
width: 600px;
margin: 0 auto;
}
.todo-container .todo-wrap {
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
Header-index.jsx:
import React, { Component } from \'react\';
import PropTypes from \'prop-types\'
import { nanoid } from \'nanoid\'
import \'./index.css\'
class Header extends Component {
// 对接收的props进行:类型,必要性的限制
static propType = {
addTodo: PropTypes.func.isRequired
}
// 键盘事件的回调
handleKeyUp = (event) => {
// console.log(event.key, event.keyCode)
// 解构赋值获取 keyCode, target
const { key, target } = event
// 判断是否是回车按键
if (key !== \'Enter\') return
// 添加的todo名字不能为空
if (target.value.trim() === \'\') {
alert(\'输入不能为空\')
return
}
// 准备好一个todo对象
const todoObj = { id: nanoid(), name: target.value, done: false }
// 将todoObj传递给App
this.props.addTodo(todoObj)
// 清空输入
target.value = \'\'
}
render() {
return (
<div className=\"todo-header\">
<input onKeyUp={this.handleKeyUp} type=\"text\" placeholder=\"请输入你的任务名称,按回车键确认\" />
</div>
);
}
}
export default Header;
Header.css:
/*header*/
.todo-header input {
width: 560px;
height: 28px;
font-size: 14px;
border: 1px solid #ccc;
border-radius: 4px;
padding: 4px 7px;
}
.todo-header input:focus {
outline: none;
border-color: rgba(82, 168, 236, 0.8);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
}
List-index.jsx:
import React, { Component } from \'react\';
import PropTypes from \'prop-types\'
import Item from \'../Item\';
import \'./index.css\'
export default class List extends Component {
// 对接收的props进行:类型,必要性的限制
static propTypes = {
todos: PropTypes.array.isRequired,
updateTodo: PropTypes.func.isRequired,
deleteTodo: PropTypes.func.isRequired
}
render() {
// 接收父组件传过来的todos
const { todos, updateTodo, deleteTodo } = this.props
return (
<ul className=\"todo-main\">
{/* 遍历todos */}
{
// todo: todos里的每一项
todos.map((todo) => {
return <Item key={todo.id} {...todo} updateTodo={updateTodo} deleteTodo={deleteTodo} />
// {...todo} ==> id={todo.id} name={todo.name} done={this.done}
})
}
</ul>
);
}
}
List.css:
/*main*/
.todo-main {
margin-left: 0px;
border: 1px solid #ddd;
border-radius: 2px;
padding: 0px;
}
.todo-empty {
height: 40px;
line-height: 40px;
border: 1px solid #ddd;
border-radius: 2px;
padding-left: 5px;
margin-top: 10px;
}
Item-index.jsx:
import React, { Component } from \'react\';
import \'./index.css\'
export default class Item extends Component {
// 标识鼠标移入,移出
state = { mouse: false }
// 鼠标移入,移出的回调
handleMouse = (flag) => {
return () => {
this.setState({ mouse: flag })
}
}
// 勾选,取消勾选某一个todo的回调
handleCheck = (id) => {
return (event) => {
// 拿到需要勾选或取消勾选的 id 和 是要勾选或者取消勾选的布尔值
// console.log(id, event.target.checked)
this.props.updateTodo(id, event.target.checked)
}
}
// 删除一个todo的回调
handleDelete = (id) => {
return () => {
if (window.confirm(\'确定删除吗?\')) {
this.props.deleteTodo(id)
}
}
}
render() {
const { id, name, done } = this.props
return (
<li style={{ backgroundColor: this.state.mouse ? \'#ddd\' : \'white\' }}
onMouseEnter={this.handleMouse(true)} onMouseLeave={this.handleMouse(false)} >
<label>
{/* defaultChecked:只在初次渲染时生效,更新时不受控制 */}
<input type=\"checkbox\" checked={done} onChange={this.handleCheck(id)} />
<span>{name}</span>
</label>
<button className=\"btn btn-danger\" onClick={this.handleDelete(id)}
style={{ display: this.state.mouse ? \'block\' : \'none\' }}>删除</button>
</li>
);
}
}
Item.css:
/*item*/
li {
list-style: none;
height: 36px;
line-height: 36px;
padding: 0 5px;
border-bottom: 1px solid #ddd;
}
li label {
float: left;
cursor: pointer;
}
li label li input {
vertical-align: middle;
margin-right: 6px;
position: relative;
top: -1px;
}
li button {
float: right;
display: none;
margin-top: 3px;
}
li:before {
content: initial;
}
li:last-child {
border-bottom: none;
}
Footer-index.jsx:
import React, { Component } from \'react\';
import \'./index.css\'
class Footer extends Component {
// 全选checkbox的回调
handleCheckAll = (event) => {
this.props.checkAllTodo(event.target.checked)
}
// 清除已完成任务的回调
handleClearAllDone = () => {
this.props.clearAllDone()
}
render() {
const { todos } = this.props
// 计算已完成的个数
const doneCount = todos.reduce((pre, todo) => {
return pre + (todo.done ? 1 : 0)
}, 0)
// console.log(doneCount)
// 总数
const total = todos.length
return (
<div className=\"todo-footer\">
<label>
<input type=\"checkbox\" onChange={this.handleCheckAll}
checked={doneCount === total && total !== 0 ? true : false} />
</label>
<span>
<span>已完成{doneCount}</span> / 全部{total}
</span>
<button onClick={this.handleClearAllDone} className=\"btn btn-danger\">清除已完成任务</button>
</div>
);
}
}
export default Footer;
Footer.css:
/*footer*/
.todo-footer {
height: 40px;
line-height: 40px;
padding-left: 6px;
margin-top: 5px;
}
.todo-footer label {
display: inline-block;
margin-right: 20px;
cursor: pointer;
}
.todo-footer label input {
position: relative;
top: -1px;
vertical-align: middle;
margin-right: 5px;
}
.todo-footer button {
float: right;
margin-top: 5px;
}
今天的分享就到这里啦