React Hook 实战指南!(2)

Todolist实例组件结构构建

我已经悄咪的完成了整个todoList解构的构建了,放出来给你们参考一下,先是目录部分:javascript

image.png

解释一下每一个文件的用途:css

  1. index.js  TodoList根组件
  2. index.scss 样式处理
  3. particles 存放全部子组件
  4. TodoListContent.js 存放todoItem的容器组件
  5. TodoListItem.js 每个TodoItem组件
  6. TodoListDes.js Todolist描述信息组件
  7. TodoListCAT.js 新建与编辑Item的组件

本次实例是利用Ant Design快速构建的,因此界面不必定好看,你们能够看到个人组件划分的层级很平,甚至还有点不合理,哈哈,实际上是为了更好的展现Hook多个场景的使用的,请你们忽略组件这么划分是否实用。java

展现一下完成品的功能吧:react

2019-09-05 15.26.53.gif

操做有点快,其实就是描述了这个应用的功能,能够新建todo,编辑todo,删除todo。展现的时候能够分页展现,标题下记录着所有todo的相关信息,而且数据都保存在LocalStorage中,就这么简单,接下来咱们就看一看不包含数据和逻辑,只有UI展现的代码吧,由于要使用Hook,因此咱们将其所有构建为函数的形式:antd

// index.js
import { Typography, Button } from 'antd'
import TodoListContent from './particles/TodoListContent'
import TodoListDes from './particles/TodoListDes'
import TodoListCAE from './particles/TodoListCAE'

const TodoListPage = (props) => {

  return (
    <div className="page-container todolist-page">
      <Typography>
        <Typography.Title level = {3}>待办事项</Typography.Title>
        <TodoListDes/>
        <Button className="create-btn" type="primary" shape="circle" icon="plus" size="large" />
      </Typography>
      <TodoListCAE />
      <TodoListContent />
    </div>
  )
  
}

export default TodoListPage
复制代码

在实例根组件中嵌入多个子组件。函数

import { Row, Col, Pagination, Spin, Empty } from 'antd'
import TodoListItem from './TodoListItem'

const TodoListContent = memo((props) => {

  return (
    <div className="todolist-content"> <Row gutter={16} className="todolist-content__container"> <Suspense fallback={<Spin/>}> <Col className="todolist__item-col" span={6}> <TodoListItem /> </Col> </Suspense> </Row> <Pagination total={20} showTotal={(total, range) => `${range[0]}-${range[1]} of ${total} items`} pageSize={8} current={1} onChange={(page) => page} /> </div> ) }) export default TodoListContent 复制代码
import React, { memo } from 'react'
import { Card, Icon, Typography } from 'antd'
const TodoListItem = memo((props) => {
  
  return (
    <Card
      className={`todolist__item finished`}
      title={ 'hahahaha' }
      extra={<Icon type="check-circle" style={{ fontSize: '24px', color: '#ccc' }}/>}
      actions={[
        <Icon type="check" key="check" />,
        <Icon type="edit" key="edit" theme="filled" />,
        <Icon type="delete" key="delete" theme="filled" />,
      ]}
    >
      <Typography.Paragraph ellipsis={{ rows: 5 }}>hahahhahahahah</Typography.Paragraph>
    </Card>
  )

})

export default TodoListItem
复制代码
import React, { memo } from 'react'
import { Typography } from 'antd'

const TodoListDes = memo(() => {
  
  return (
    <Typography.Paragraph> 当前共有 0 条待办事项,其中0条已完成,0条待完成。 </Typography.Paragraph> ) }) export default TodoListDes 复制代码

Ok,这里是实例构成的代码,里面有几个不常见的API的使用,例如:Supense,memo。其实这些都是React 16.4之后提出的一些新的API,建议你们去学习一下,在这里我就不介绍了,若是不明白也不肯意去查文档的话,其实彻底能够忽略掉个人代码中的这些内容(并不影响任何功能)。学习