React 中级阶段学习计划

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}><inputtype="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.mzph.cn/web/55583.shtml

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

相关文章

gitlab配置ssh密钥

1.配置用户信息 git config --global user.name "你的名字" git config --global user.email "你的邮箱" 查看配置是否成功 git config --global --list 2.生成密钥 终端 或 右键文件夹open git bash here 输入命令 ssh-keygen -t rsa -C 随意(生…

接口测试(二)jmeter——实现http请求、察看结果树、请求默认值

一、实现http请求&#xff0c;察看结果树 1. 测试计划 --> 添加 --> 线程(用户) --> 线程组 2. 线程组配置 默认配置 线程数&#xff1a;虚拟用户数&#xff0c;一个虚拟用户占用一个进程或线程。 Ramp-Up 时间&#xff08;秒&#xff09;&#xff1a;全部线程执行完…

使用Jenkins部署项目

部署中的痛点 为什么要用Jenkins&#xff1f;我说下我以前开发的痛点&#xff0c;在一些中小型企业&#xff0c;每次开发一个项目完成后&#xff0c;需要打包部署&#xff0c;可能没有专门的运维人员&#xff0c;只能开发人员去把项目打成一个exe包&#xff0c;可能这个项目已…

Kettle基本使用

目录 一、安装Kelttle 1-1 安装java环境 1-2 Kettle安装 二、Kettle的基本使用 2-1 将txt文本数据转为excel数据 创建txt文件 创建kettle的转换任务 定义转换流程 配置输入文件 连接读取和写入任务 配置excel输出 保存转换任务 执行转换任务 2-2 将txt文件输出到M…

数据库管理-第252期 深入浅出多主多活数据库技术- Cantian存储引擎(二)(20241017)

数据库管理252期 2024-10-17 数据库管理-第252期 深入浅出多主多活数据库技术- Cantian存储引擎&#xff08;二&#xff09;&#xff08;20241017&#xff09;1 部署规划2 服务器基础配置2.1 配置HOSTS2.2 关闭防火墙2.3 关闭SELinux2.4 配置yum源 3 编译服务器配置3.1 安装git…

「Python精品教程」Python快速入门,基础数据结构:数字

​***奕澄羽邦精品教程系列*** 编程环境&#xff1a; 1、Python 3.12.5 2、Visual Studio Code 1.92.1 在现实世界中&#xff0c;我们经常要面对各式各样的数字&#xff0c;通过简单或者复杂的数学运算&#xff0c;来帮助我们计算出想要的结果。程序开发过程中&#xff0c;数字…

自动化测试工具在API测试中的优势是什么?

在设计API接口时&#xff0c;确保数据获取的效率和准确性是至关重要的。以下是一些最佳实践和代码示例&#xff0c;帮助你提高API的数据获取效率和准确性。 1. 使用高效的数据访问模式 选择合适的数据库访问模式对于提高数据获取效率至关重要。例如&#xff0c;使用索引可以显…

【启明智显分享】ZX7981PM WIFI6 5G-CPE:2.5G WAN口,2.4G/5G双频段自动调速

昨天&#xff0c;我们向大家展现了ZX7981PG WIFI6 5G-CPE&#xff0c;它强大的性能也引起了一波关注&#xff0c;与此同时&#xff0c;我们了解到部分用户对更高容量与更高速网口的需求。没关系&#xff01;启明智显早就预料到了&#xff01;ZX7981PM满足你的需求&#xff01; …

Vue3 集成Monaco Editor编辑器

Vue3 集成Monaco Editor编辑器 1. 安装依赖2. 使用3. 效果 Monaco Editor &#xff08;官方链接 https://microsoft.github.io/monaco-editor/&#xff09;是一个由微软开发的功能强大的在线代码编辑器&#xff0c;被广泛应用于各种 Web 开发场景中。以下是对 Monaco Editor 的…

HTML5教程(三)- 常用标签

1 文本标签-h 标题标签&#xff08;head&#xff09;&#xff1a; 自带加粗效果&#xff0c;从h1到h6字体大小逐级递减一个标题独占一行 语法 <h1>一级标题</h1><h2>二级标题</h2><h3>三级标题</h3><h4>四级标题</h4><h5…

关于md5强比较和弱比较绕过的实验

在ctf比赛题中我们的md5强弱比较的绕过题型很多&#xff0c;大部分都是结合了PHP来进行一个考核。这一篇文章我将讲解一下最基础的绕过知识。 MD5弱比较 比较的步骤 在进行弱比较时&#xff0c;PHP会按照以下步骤执行&#xff1a; 确定数据类型&#xff1a;检查参与比较的两…

jmeter响应断言放进csv文件遇到的问题

用Jmeter的json 断言去测试http请求响应结果&#xff0c;发现遇到中文时出现乱码&#xff0c;导致无法正常进行响应断言&#xff0c;很影响工作。于是&#xff0c;察看了其他测试人员的解决方案&#xff0c;发现是jmeter本身对编码格式的设置导致了这一问题。解决方案是在jmete…

【文化课学习笔记】【化学】选必三:同分异构体的书写

【化学】选必三&#xff1a;同分异构体的书写 如果你是从 B 站一化儿笔记区来的&#xff0c;请先阅读我在第一篇有机化学笔记中的「读前须知」(点开头的黑色小三角展开)&#xff1a;链接 链状烃的取代和插空法 取代法 一取代物 甲烷、乙烷、丙烷、丁烷的种类 甲烷&#xff1a;只…

游戏逆向基础-找释放技能CALL

思路&#xff1a;通过send断点然后对send的data参数下写入断点找到游戏里面的技能或者攻击call 进入游戏先选好一个怪物&#xff08;之所以要先选好是因为选怪也会断&#xff0c;如果直接左键打怪的话就会断几次&#xff09; 断下来后对参数下硬件写入断点 硬件断点断下来后先…

如何用pyhton修改1000+图片的名字?

import os oldpath input("请输入文件路径&#xff08;在windows中复制那个图片文件夹的路径就可以):") #注意window系统中的路径用这个‘\分割&#xff0c;但是编程语言中一般都是正斜杠也就是’/‘ #这里写一个代码&#xff0c;将 \ > / path "" fo…

基于SpringBoot+Vue+uniapp的海产品加工销售一体化管理系统的详细设计和实现(源码+lw+部署文档+讲解等)

详细视频演示 请联系我获取更详细的视频演示 项目运行截图 技术框架 后端采用SpringBoot框架 Spring Boot 是一个用于快速开发基于 Spring 框架的应用程序的开源框架。它采用约定大于配置的理念&#xff0c;提供了一套默认的配置&#xff0c;让开发者可以更专注于业务逻辑而不…

基于FPGA的DDS信号发生器(图文并茂+深度原理解析)

篇幅有限,本文详细源文件已打包 至个人主页资源,需要自取...... 前言 DDS(直接数字合成)技术是先进的频率合成手段,在数字信号处理与硬件实现领域作用关键。它因低成本、低功耗、高分辨率以及快速转换时间等优点备受认可。 本文着重探究基于 FPGA 的简易 DDS 信号发生器设…

交叉熵损失 在PyTorch 中的计算过程

其实就是根据 真实值的结果&#xff0c;当成索引去取的值 import torch import torch.nn as nnaaaa torch.tensor([[2.0,1.0,3.0],[2.0,4.0,2.0]])l1 nn.LogSoftmax(dim-1) result l1(aaaa) print(result) import torch import torch.nn as nn# 定义交叉熵损失函数 criterio…

数据治理为何如此简单?

欢迎来文末免费获取数据治理相关PPT和文档 引言 随着大数据技术的迅速发展&#xff0c;企业积累的数据量呈现爆炸式增长。有效的数据管理已经成为企业提高决策效率、增强竞争优势的重要手段。在这样的背景下&#xff0c;数据治理逐渐成为企业数据管理中不可或缺的一环。它不仅…

查看SQL执行计划 explain

查看SQL执行计划 explain explain使用方式 alter session set current_schematest; explain plan for sql语句; --并不会实际执行&#xff0c;因此生成的执行计划也是预估的 select * from table(dbms_xplan.display); explain使用场景 1.内存中没有谓词信息了&#xff0…