React 中级阶段学习计划

news2024/10/22 7:10:24

React 中级阶段学习计划

目标

  • 掌握状态管理和路由。
  • 能够调用API并处理异步数据。
  • 学会使用CSS-in-JS和CSS Modules进行样式处理。

学习内容

状态管理

React Context API
  • Context API:用于在组件树中传递数据,避免多层props传递。
  • 示例
    import React, { createContext, useContext, useState } from 'react';
    
    // 创建Context
    const ThemeContext = createContext();
    
    // 提供者组件
    function ThemeProvider({ children }) {
      const [theme, setTheme] = useState('light');
    
      const toggleTheme = () => {
        setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
      };
    
      return (
        <ThemeContext.Provider value={{ theme, toggleTheme }}>
          {children}
        </ThemeContext.Provider>
      );
    }
    
    // 消费者组件
    function App() {
      const { theme, toggleTheme } = useContext(ThemeContext);
    
      return (
        <div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>
          <h1>Current Theme: {theme}</h1>
          <button onClick={toggleTheme}>Toggle Theme</button>
        </div>
      );
    }
    
    function Root() {
      return (
        <ThemeProvider>
          <App />
        </ThemeProvider>
      );
    }
    
    export default Root;
    
    
Redux
  • Redux:一个用于管理应用状态的库,适用于大型应用。
  • 安装
    npm install redux react-redux
    
  • 示例
    import React from 'react';
    import { createStore } from 'redux';
    import { Provider, useSelector, useDispatch } from 'react-redux';
    
    // Reducer
    const counterReducer = (state = { count: 0 }, action) => {
      switch (action.type) {
        case 'INCREMENT':
          return { ...state, count: state.count + 1 };
        case 'DECREMENT':
          return { ...state, count: state.count - 1 };
        default:
          return state;
      }
    };
    
    // Store
    const store = createStore(counterReducer);
    
    // Action Creators
    const increment = () => ({ type: 'INCREMENT' });
    const decrement = () => ({ type: 'DECREMENT' });
    
    // Component
    function Counter() {
      const count = useSelector((state) => state.count);
      const dispatch = useDispatch();
    
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={() => dispatch(increment())}>Increment</button>
          <button onClick={() => dispatch(decrement())}>Decrement</button>
        </div>
      );
    }
    
    function App() {
      return (
        <Provider store={store}>
          <Counter />
        </Provider>
      );
    }
    
    export default App;
    

路由

React Router
  • React Router:用于在React应用中实现页面导航。
  • 安装
    npm install react-router-dom
    
  • 示例
    import React from 'react';
    import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
    
    // 页面组件
    function Home() {
      return <h2>Home</h2>;
    }
    
    function About() {
      return <h2>About</h2>;
    }
    
    function Contact() {
      return <h2>Contact</h2>;
    }
    
    // 主组件
    function App() {
      return (
        <Router>
          <div>
            <nav>
              <ul>
                <li><Link to="/">Home</Link></li>
                <li><Link to="/about">About</Link></li>
                <li><Link to="/contact">Contact</Link></li>
              </ul>
            </nav>
    
            <Switch>
              <Route path="/" exact component={Home} />
              <Route path="/about" component={About} />
              <Route path="/contact" component={Contact} />
            </Switch>
          </div>
        </Router>
      );
    }
    
    export default App;
    

API调用

使用fetch和axios
  • fetch:浏览器内置的API调用方法。
  • axios:一个基于Promise的HTTP客户端,支持浏览器和Node.js。
  • 安装axios
    npm install axios
    
  • 示例
    import React, { useState, useEffect } from 'react';
    import axios from 'axios';
    
    function FetchData() {
      const [data, setData] = useState(null);
    
      useEffect(() => {
        axios.get('https://jsonplaceholder.typicode.com/posts')
          .then(response => {
            setData(response.data);
          })
          .catch(error => {
            console.error('Error fetching data:', error);
          });
      }, []);
    
      return (
        <div>
          <h1>Data from API</h1>
          {data ? (
            <ul>
              {data.map(item => (
                <li key={item.id}>{item.title}</li>
              ))}
            </ul>
          ) : (
            <p>Loading...</p>
          )}
        </div>
      );
    }
    
    export default FetchData;
    

样式处理

CSS-in-JS
  • styled-components:一个流行的CSS-in-JS库。
  • 安装
    npm install styled-components
    
  • 示例
    import React from 'react';
    import styled from 'styled-components';
    
    const Button = styled.button`
      background-color: ${props => props.primary ? 'blue' : 'white'};
      color: ${props => props.primary ? 'white' : 'black'};
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    `;
    
    function App() {
      return (
        <div>
          <Button primary>Primary Button</Button>
          <Button>Secondary Button</Button>
        </div>
      );
    }
    
    export default App;
    
CSS Modules
  • CSS Modules:允许你编写局部作用域的CSS。
  • 示例
    // Button.module.css
    .button {
      background-color: white;
      color: black;
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
    
    .primary {
      background-color: blue;
      color: white;
    }
    
    // Button.js
    import React from 'react';
    import styles from './Button.module.css';
    
    function Button({ primary, children }) {
      return (
        <button className={`${styles.button} ${primary ? styles.primary : ''}`}>
          {children}
        </button>
      );
    }
    
    export default Button;
    
    // App.js
    import React from 'react';
    import Button from './Button';
    
    function App() {
      return (
        <div>
          <Button primary>Primary Button</Button>
          <Button>Secondary Button</Button>
        </div>
      );
    }
    
    export default App;
    

实践项目

待办事项列表

  1. 创建项目
    npx create-react-app todo-list
    cd todo-list
    npm start
    
  2. 创建组件
    • TodoForm.js:添加待办事项的表单
      import React, { useState } from 'react';
      
      function TodoForm({ addTodo }) {
        const [value, setValue] = useState('');
      
        const handleSubmit = (e) => {
          e.preventDefault();
          if (!value) return;
          addTodo(value);
          setValue('');
        };
      
        return (
          <form onSubmit={handleSubmit}>
            <input
              type="text"
              className="input"
              value={value}
              onChange={(e) => setValue(e.target.value)}
              placeholder="Add a new task"
            />
            <button type="submit" className="button">Add</button>
          </form>
        );
      }
      
      export default TodoForm;
      
    • TodoList.js:显示待办事项列表
      import React from 'react';
      
      function TodoList({ todos, removeTodo }) {
        return (
          <div>
            {todos.map((todo, index) => (
              <div key={index} className="todo">
                <span>{todo}</span>
                <button onClick={() => removeTodo(index)}>Delete</button>
              </div>
            ))}
          </div>
        );
      }
      
      export default TodoList;
      
    • App.js:主组件
      import React, { useState } from 'react';
      import TodoForm from './TodoForm';
      import TodoList from './TodoList';
      
      function App() {
        const [todos, setTodos] = useState([]);
      
        const addTodo = (text) => {
          const newTodos = [...todos, text];
          setTodos(newTodos);
        };
      
        const removeTodo = (index) => {
          const newTodos = [...todos];
          newTodos.splice(index, 1);
          setTodos(newTodos);
        };
      
        return (
          <div className="app">
            <div className="todo-list">
              <h1>Todo List</h1>
              <TodoForm addTodo={addTodo} />
              <TodoList todos={todos} removeTodo={removeTodo} />
            </div>
          </div>
        );
      }
      
      export default App;
      

电子商务网站

  1. 创建项目
    npx create-react-app ecommerce
    cd ecommerce
    npm start
    
  2. 安装axios
    npm install axios
    
  3. 创建组件
    • ProductList.js:显示产品列表
      import React, { useState, useEffect } from 'react';
      import axios from 'axios';
      
      function ProductList() {
        const [products, setProducts] = useState([]);
      
        useEffect(() => {
          axios.get('https://fakestoreapi.com/products')
            .then(response => {
              setProducts(response.data);
            })
            .catch(error => {
              console.error('Error fetching products:', error);
            });
        }, []);
      
        return (
          <div className="product-list">
            {products.map(product => (
              <div key={product.id} className="product">
                <img src={product.image} alt={product.title} />
                <h3>{product.title}</h3>
                <p>${product.price}</p>
              </div>
            ))}
          </div>
        );
      }
      
      export default ProductList;
      
    • App.js:主组件
      import React from 'react';
      import ProductList from './ProductList';
      
      function App() {
        return (
          <div className="App">
            <h1>E-commerce Website</h1>
            <ProductList />
          </div>
        );
      }
      
      export default App;
      

建议

  • 定期回顾:每周花时间回顾本周所学内容,确保知识点牢固掌握。
  • 参与社区:加入React相关的论坛、Slack群组或Discord服务器,与其他开发者交流心得。
  • 阅读源码:尝试阅读一些简单的React库的源码,提高代码理解和分析能力。

希望这个学习计划能够帮助你系统地学习React中级技能,并通过实践项目巩固所学知识。祝你学习顺利!


你可以将上述Markdown内容复制到任何支持Markdown的编辑器或平台中,以便于查看和使用。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2220628.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

监控易监测对象及指标之:Kafka中间件JMX监控指标解读

监控易作为一款功能强大的监控软件&#xff0c;旨在为企业提供全方位的IT系统监控服务。其中&#xff0c;针对Kafka中间件的JMX监控是监控易的重要功能之一。本文将详细解读监控易中Kafka的JMX监控指标&#xff0c;帮助企业更好地理解并运用这些数据进行系统性能调优和故障排查…

onlyoffice docker启用jwt并生成jwt

一、说明 本文是docker教程&#xff0c;linux/win的安装版本也类似&#xff0c;只需要修改配置文件中的secrt就可以了【Configuring JWT for ONLYOFFICE Docs - ONLYOFFICE】 二、正文开始 docker启动时候如果不想使用jwt&#xff0c;加上参数-e JWT_ENABLEDfalse就可以了&…

软件I2C的代码

I2C的函数 GPIO的配置——scl和sda都配置为开漏输出 void MyI2C_Init(void) {RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);GPIO_InitTypeDef GPIO_InitStruture;GPIO_InitStruture.GPIO_Mode GPIO_Mode_Out_OD;GPIO_InitStruture.GPIO_PinGPIO_Pin_10 | GPIO_Pin_…

Maven 项目管理工具

目录 Maven简介 Maven快速上手 Maven详细介绍 Maven工作机制 Maven安装及配置 使用IDEA创建Maven Web工程 Maven简介 Maven是 Apache 开源组织奉献的一个开源项目&#xff0c;可以翻译为“专家”或“内行”。 Maven 的本质是一个项目管理工具&#xff0c;将项目开发和管…

Ansible自动化工具

一、Ansible概述 1.1 什么是Ansible Ansible 是一个开源的自动化工具&#xff0c;用于配置管理、应用程序部署和任务自动化。它让你可以通过编写简单的 YAML 文件&#xff08;剧本&#xff0c;Playbooks&#xff09;&#xff0c;轻松管理和配置多个服务器。Ansible 的特点是无…

爬虫逆向-js进阶(续写,搭建网站)

1.搭建简单网站1 from flask import Flask,render_template import requests import json app Flask(name)# **location**的温度是**temp**度&#xff0c;天气状况&#xff1a;**desc**app.route(/) # 绑定处理函数 def index_url():location 101010100data get_weather(lo…

Rust语言编程环境的安装

简介 Rust是一门系统编程语言,专注于安全,尤其是并发安全,支持函数式和命令式以及泛型等编程范式的多范式语言。 Rust语言的特点 系统级编程:Rust语言非常适合进行底层系统级编程,如操作系统、网络协议栈、设备驱动程序等。 内存安全:Rust使用所有权(ownership)系统来…

Scrapy | 爬取笑话网来认识继承自Spider的crawlspider爬虫类

crawlspider 1. 创建crawlspider爬虫2. 实战-爬取笑话网笑话 本篇内容旨在拓展视野和知识&#xff0c;了解crawlspider的使用即可&#xff0c;主要熟悉掌握spider类的使用 CrawlSpider 提供了一种更高级的方法来定义爬取规则&#xff0c;而无需编写大量的重复代码。它基于规则…

【功能安全】汽车功能安全个人认证证书

目录 1、证书 2、课程信息 &#x1f4d6; 推荐阅读 1、证书 汽车功能安全工程师去拿类似莱茵、SGS、南德颁发的证书&#xff0c;如下&#xff1a; 2、课程信息 一般上什么课程了&#xff0c;课程信息大概如下&#xff1a; 汽车功能安全工程师认证课 &#xff08;3天&#…

【Linux】进程的挂起状态

挂起状态的前提条件 当 内存资源严重不足 时&#xff0c;操作系统会考虑将部分进程换出到磁盘上的交换空间&#xff08;swap 分区&#xff09;。这通常发生在以下几种情况下&#xff1a; 内存不足&#xff1a; 当物理内存接近耗尽时&#xff0c;操作系统会选择将一部分暂时不需…

查缺补漏----数据结构树高总结

① 对于平衡二叉树而言&#xff0c;树高的规律&#xff1a; 高度为h的平衡二叉树的含有的最少结点数&#xff08;所有非叶节点的平衡因子均为1&#xff09;&#xff1a; n01&#xff0c;n11&#xff0c;n22 含有的最多结点数&#xff1a; (高度为h的满二叉树含有的结点数) ②…

监控内容、监控指标、监控工具大科普

在现代信息技术领域&#xff0c;监控技术扮演着至关重要的角色。它帮助我们实时了解系统、网络、应用以及环境的状态&#xff0c;确保它们的安全、稳定和高效运行。以下是对监控内容、监控指标和监控工具的详细科普。 一、监控内容 监控内容是指监控系统所关注和记录的具体信…

C++面向对象编程学习

C面向对象编程学习 前言一、C面向对象编程二、知识点学习1. 定义一个类1.1 使用struct定义1.2 使用class定义1.3 struct和class的区别 2. 类的定义方式2.1 单文件定义&#xff08;Inline Definition&#xff09;2.2 分离定义&#xff08;Separate Definition&#xff09;2.3 头…

一文2500字从0到1实现压测自动化!

大家好&#xff0c;我是小码哥&#xff0c;最近工作有点忙&#xff0c;一直在实现压测自动化的功能&#xff0c;今天来分享一下实现思路 我所在的业务线现在项目比较少了&#xff0c;所以最近一个月我都没有做业务测试&#xff0c;需求开发完后RD直接走免测就上线&#xff0c;…

利用Spring Boot实现信息化教学平台

1系统概述 1.1 研究背景 随着计算机技术的发展以及计算机网络的逐渐普及&#xff0c;互联网成为人们查找信息的重要场所&#xff0c;二十一世纪是信息的时代&#xff0c;所以信息的管理显得特别重要。因此&#xff0c;使用计算机来管理信息化在线教学平台的相关信息成为必然。开…

Ansible自动化运维管理工具

一、Ansible 1.1、自动化运维管理工具有哪些&#xff1f; 工具架构语言使用情况Ansible无clientpython 协议用ssh95%puppetC/Sruby 协议用http基本不用chefC/Sruby 协议用http基本不用saltstackC/Spython 协议用ssh5% 1.2、Ansible简介 Ansible是一个基于Py…

深度学习 简易环境安装(不含Anaconda)

在Windows上安装深度学习环境而不使用Anaconda&#xff0c;下面是一个基于pip的安装指南&#xff1a; 1. 安装Python 确保你已经安装了Python。可以从Python官网下载Python&#xff0c;并在安装时勾选“Add Python to PATH”选项。 注意&#xff0c;Python 不要安装最新版的…

期权懂|期权止损策略如何平衡风险与收益?

本期让我懂 你就懂的期权懂带大家来了解&#xff0c;期权止损策略如何平衡风险与收益&#xff1f;有兴趣的朋友可以看一下。期权小懂每日分享期权知识&#xff0c;帮助期权新手及时有效地掌握即市趋势与新资讯&#xff01; 期权止损策略如何平衡风险与收益&#xff1f; 期权止损…

如何写一个视频编码器演示篇

先前写过《视频编码原理简介》&#xff0c;有朋友问光代码和文字不太真切&#xff0c;能否补充几张图片&#xff0c;今天我们演示一下&#xff1a; 这是第一帧画面&#xff1a;P1&#xff08;我们的参考帧&#xff09; 这是第二帧画面&#xff1a;P2&#xff08;需要编码的帧&…

计算机网络—静态路由

1.0 网络拓扑结构 星型拓扑结构是一个中心&#xff0c;多个分节点。它结构简单&#xff0c;连接方便&#xff0c;管理和维护都相对容易&#xff0c;而且扩展性强。网络延迟时间较小&#xff0c;传输误差低。中心无故障&#xff0c;一般网络没问题。中心故障&#xff0c;网络就出…