React 学习 第七天

127 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

项目实例--租房移动Web

1.项目准备

  1. 项目介绍

    • 租房-移动Web端
    • 项目介绍:项目是一个在线租房项目,实现了类似链家等项目的功能,解决用户租房需求
    • 核心业务:在线找房(地图、条件搜索)、用户登录、房源发布等
  2. 技术栈

    • React核心库:react、react-dom、react-router-dom
    • 脚手架:create-react-app
    • 数据请求:axios
    • UI组件库:antd-mobile
    • 其他组件库:react-virtualized、formik+yup、react-spring等
    • 百度地图API
  3. 项目搭建

    • 导入数据:数据库名称hkzf
    • 启动接口:在API目录中执行npm start
  4. 组件库antd-mobile

    • 安装 npm install antd-mobile --save

    • 在自己的组件中导入要使用的组件

    • 渲染组件

      import { Button } from 'antd-mobile'
      
      import 'antd-mobile/dist/antd-mobile.css'
      
      <Button />
      
  5. 配置基础路由

    1. 安装路由:npm install react-router-dom

    2. 导入路由组件:Router/Router/Link

    3. 在pages文件夹中创建Home/index.js和CityList/index.js两个组件

      import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
      
      <Route path="/home" component={Home} />
      <Route path="/citylist" component={CityList} />
      
    4. 新版本Router使用心得

      /*
      	1. 新版本的Route使用时需要包裹在Routes中才能使用
      	2. 新版本的Route不在使用component属性,而使用element属性,并且组件需要带<>才会显示
      */
      
      
    5. 外观和样式调整

      1. 修改页面标题:在index.html中修改
      2. 基础样式调整:在index.css中修改

2.项目整体布局

  1. 两步布局页面

    • 有TabBar的页面:首页、找房、咨询、我的
    • 无TabBar的页面:城市选择等
  2. 嵌套路由

    • 嵌套路由:路由内部包含路由

      /*
      	1. 新版本使用嵌套路由时,直接在父路由中添加子节点
      	2. 父组件中添加<Outlet />标记
      */
      
      App.js
      
      <Route path="/home" element={<Home />}>
      	<Route path="news" element={<News />}></Route>
      </Route>
          
      Home.js
      
      <div>
      	<h1>这是个Home主页</h1>
      	<Outlet />
      </div>
      
  3. 实现TarBar

    • 使用antd-mobile中TabBar组件,参考使用文档
  4. TabBar配合路由使用

3.首页模块

  1. 首页路由处理

    /*
    	1.配置默认路由
    	2.React-Router@6 中element代替component,并且使用Navigate代替Redirect重定向
    */ 
    <Route exact path="/" element={ <Navigate replace to="/home" /> }>
    </Route>
    
    /*
    	1.Home组件中的跳转Index页面,默认为主页,即是/home/index => /home
    	
    	
    */