React系列文章导航
一. Todo案例
本篇文章主要是做一个Demo,功能如下:
- 显示所有的Todo列表。
- 输入文本,点击按钮显示到列表的收尾,并清除输入的文本。
初始架构图如下(其他文件夹中没有文件):
App.jsx
代码:
// 创建外壳组件App
import React, { Component } from 'react'
import './App.css'
// 暴露App组件,其他Js就可以引用了
export default class App extends Component {
render() {
return (
<div className="todo-container">
<div className="todo-wrap">
<div className="todo-header">
<input type="text" placeholder="请输入你的任务名称,按回车键确认" />
</div>
<ul className="todo-main">
<li>
<label>
<input type="checkbox" />
<span>xxxxx</span>
</label>
<button className="btn btn-danger" style={{ display: 'none' }}>删除</button>
</li>
<li>
<label>
<input type="checkbox" />
<span>yyyy</span>
</label>
<button className="btn btn-danger" style={{ display: 'none' }}>删除</button>
</li>
</ul>
<div className="todo-footer">
<label>
<input type="checkbox" />
</label>
<span>
<span>已完成0</span> / 全部2
</span>
<button className="btn btn-danger">清除已完成任务</button>
</div>
</div>
</div>
)
}
}
App.css
代码:提取码z9pj
index.js
代码:
// 引入React核心库
import React from 'react'
// 引入ReactDOM
import ReactDOM from 'react-dom'
// 引入App组件
import App from './App'
// 渲染App到页面
ReactDOM.render(<App />, document.getElementById('root'))
页面效果如下:
目标,将App.jsx
文件以及App.css
文件中的代码进行组件分离:
最后分离的架构图如下:
代码:rx0h
放出部分比较直观的代码:
Item
:
分离之后,紧接着对项目的各个功能进行编写,对于项目我们分为4个部分:
1.1 组件的具体实现
1.1.1 Header
安装nanoid:
npm install nanoid
Jsx
:
import React, { Component } from 'react';
import { nanoid } from 'nanoid'
import './index.css'
import PropTypes from 'prop-types'
class Header extends Component {
static propTypes = {
addTodo: PropTypes.func.isRequired
}
handleKeyUp = (event) => {
// 1.结构赋值
const { keyCode, target } = event
// 2.判断是否按下了回车键,回车按键的编号是13
if (keyCode !== 13) return
// 3.判断添加的todo名字是否为空
if (target.value.trim() === '') {
alert('输入不能为空!')
return
}
// 4.准备一个todo对象,nanoid()会随机生成一个UUID
const todoObj = { id: nanoid(), name: target.value, done: false }
// 5.将todoObj传递给App
this.props.addTodo(todoObj)
// 6.清空输入框
target.value = ''
}
render() {
return (
<div className="todo-header">
{/*onKeyUp指的是按键操作*/}
<input onKeyUp={this.handleKeyUp} type="text" placeholder="请输入你的任务名称,按回车键确认" />
</div>
);
}
}
export default Header;
css
:
.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);
}
1.1.2 List
Jsx
:
import React, { Component } from 'react';
import Item from '../Item'
import PropTypes from 'prop-types'
import './index.css'
class List extends Component {
static propTypes = {
todos: PropTypes.array.isRequired,
updateTodo: PropTypes.func.isRequired,
deleteTodo: PropTypes.func.isRequired,
}
render() {
const { todos, updateTodo, deleteTodo } = this.props
return (
<ul className="todo-main">
{
todos.map(todo => {
return <Item key={todo.id} {...todo} updateTodo={updateTodo} deleteTodo={deleteTodo} />
})
}
</ul>
);
}
}
export default List;
Css
:
.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;
}
1.1.3 Item
Jsx
:
import React, { Component } from 'react';
import './index.css'
class Item extends Component {
state = { mouse: false }
// 标识鼠标的出入事件
handleMouse = (flag) => {
return () => {
this.setState({ mouse: flag })
}
}
// 对于多选框勾选的回调函数
handleCheck = (id) => {
return (event) => {
this.props.updateTodo(id, event.target.checked)
}
}
handleDelete = (id) => {
// 点击确定,则进行删除,若取消则不删除,会进行一个弹框
if (window.confirm('确定删除吗?')) {
this.props.deleteTodo(id)
}
}
render() {
const { id, name, done } = this.props
const { mouse } = this.state
return (
// onMouseLeave 鼠标移除事件 onMouseEnter 鼠标移入事件
<li style={{ backgroundColor: mouse ? '#ddd' : 'white' }} onMouseLeave={this.handleMouse(false)} onMouseEnter={this.handleMouse(true)}>
<label>
<input type="checkbox" checked={done} onChange={this.handleCheck(id)} />
<span>{name}</span>
</label>
<button className="btn btn-danger" style={{ display: mouse ? 'block' : 'none' }} onClick={() => { this.handleDelete(id) }}>删除</button>
</li>
);
}
}
export default Item;
Css
:
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;
}
1.1.4 Footer
Jsx
:
import React, { Component } from 'react';
import './index.css'
class Footer extends Component {
// 全选checkBox的回调
handleCheckAll = (event) => {
this.props.checkAllTodo(event.target.checked)
}
// 清除已经完成任务的回调
handleClearAll = () => {
this.props.clearAllDone()
}
render() {
const { todos } = this.props
// 计算已经完成的个数
const doneCount = todos.reduce((pre, todo) => pre + (todo.done ? 1 : 0), 0)
// 总数
const total = todos.length
return (
<div className="todo-footer">
<label>
<input type="checkbox" checked={doneCount === total && total != 0 ? true : false} onChange={this.handleCheckAll} />
</label>
<span>
<span>已完成{doneCount}</span> / 全部{total}
</span>
<button className="btn btn-danger" onClick={this.handleClearAll}>清除已完成任务</button>
</div>
);
}
}
export default Footer;
Css
:
.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;
}
1.2 父类App组件的实现
App.jsx
:
// 创建外壳组件App
import React, { Component } from 'react'
import Header from './component/Header'
import List from './component/List'
import Footer from './component/Footer'
import './App.css'
// 暴露App组件,其他Js就可以引用了
export default class App extends Component {
state = {
todos: [
{ id: '001', name: '吃饭', done: true },
{ id: '002', name: '睡觉', done: true },
{ id: '003', name: '购物', done: false },
]
}
// 用于添加一个todo,接收了一个todo对象
addTodo = (todoObj) => {
// 获取原todo列表
const { todos } = this.state
// 追加一个todo
const newTodos = [todoObj, ...todos]
// 更新状态
this.setState({ todos: newTodos })
}
// 更新一个Todo的状态
updateTodo = (id, done) => {
const { todos } = this.state
const newTodos = todos.map((todoObj) => {
// 对指定Id的对象,修改它的done属性
if (todoObj.id === id) return { ...todoObj, done }
else return todoObj
})
this.setState({ todos: newTodos })
}
// 删除一个Todo对象
deleteTodo = (id) => {
// 1.先获取原本的todo列表
const { todos } = this.state
// 2.删除指定Id的对象
const newTodos = todos.filter(todoObj => {
return todoObj.id !== id
})
// 3.更新状态
this.setState({ todos: newTodos })
}
checkAllTodo = (done) => {
const { todos } = this.state
const newTodos = todos.map((obj) => {
// 全选后,将所有对象的状态都改为true,即已选中
return { ...obj, done }
})
this.setState({ todos: newTodos })
}
clearAllDone = () => {
const { todos } = this.state
const newTodos = todos.filter(todoObj => {
return !todoObj.done
})
this.setState({ todos: newTodos })
}
render() {
const { todos } = this.state
return (
<div className="todo-container">
<div className="todo-wrap">
<Header addTodo={this.addTodo} />
<List todos={todos} updateTodo={this.updateTodo} deleteTodo={this.deleteTodo} />
<Footer todos={todos} checkAllTodo={this.checkAllTodo} clearAllDone={this.clearAllDone} />
</div>
</div>
)
}
}
App.css
:
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;
}
入口文件index.js
:
// 引入React核心库
import React from 'react'
// 引入ReactDOM
import ReactDOM from 'react-dom'
// 引入App组件
import App from './App'
// 渲染App到页面
ReactDOM.render(<App />, document.getElementById('root'))
最后页面的效果图如下:
二. Todo案例的总结
关于父子类之间的通信:
-
父组件
给子组件
传递数据,通过props
传递。
-
子组件
给父组件
传递数据,通过props
传递,但是要求父组件
提前传递一个函数。
例如代码中:
父组件App
给子组件传递数据:
然后List
组件中通过props标签来获取对应数据:
一个组件其状态在哪里,那么操作状态的方法就应该写在哪里。
例如:本案例中,我们都是对todos
对象列表进行操作,而其定义在App
组件中:
那么后续对该状态进行操作的一些函数,都应该写在App
组件中:
而子组件中的调用,只是进行一层包装,例如:
就好比Java中,对Controller
层–>Service
层–>Dao
层…
动态初始化列表,如何确定将数据放在哪个组件的state中?
- 对于一个数据,若供给某个组件使用,那么放在该组件自身的
state
中。
- 若供给一些组件去使用,那么放在它们共同的父组件
state
中。(官方称该操作为状态提升)