00 - React 基础

1. React 基础

JSX

JSX 是一种 JavaScript 的语法扩展,类似于 XML 或 HTML,允许我们在 JavaScript 代码中编写 HTML。

const element = <h1>Hello, world!</h1>;

组件

组件是 React 应用的核心,可以是函数组件或类组件。

函数组件
function Welcome(props) {return <h1>Hello, {props.name}</h1>;
}
类组件
class Welcome extends React.Component {render() {return <h1>Hello, {this.props.name}</h1>;}
}

Props

Props(属性)是组件间传递数据的方式。

function Welcome(props) {return <h1>Hello, {props.name}</h1>;
}const element = <Welcome name="Sara" />;

State

State 是组件内部的数据管理机制,只能在类组件和使用 Hook 的函数组件中使用。

类组件中的 State
class Clock extends React.Component {constructor(props) {super(props);this.state = { date: new Date() };}render() {return <h2>It is {this.state.date.toLocaleTimeString()}.</h2>;}
}
函数组件中的 State
import { useState } from 'react';function Clock() {const [date, setDate] = useState(new Date());return <h2>It is {date.toLocaleTimeString()}.</h2>;
}

事件处理

React 的事件处理类似于 DOM 事件,但有一些语法差异。

function ActionLink() {function handleClick(e) {e.preventDefault();console.log('The link was clicked.');}return (<a href="#" onClick={handleClick}>Click me</a>);
}

2. 组件生命周期

类组件有一系列生命周期方法,可以在组件的不同阶段执行代码。

class Clock extends React.Component {constructor(props) {super(props);this.state = { date: new Date() };}componentDidMount() {this.timerID = setInterval(() => this.tick(), 1000);}componentWillUnmount() {clearInterval(this.timerID);}tick() {this.setState({date: new Date()});}render() {return <h2>It is {this.state.date.toLocaleTimeString()}.</h2>;}
}

3. React Hooks

Hooks 是 React 16.8 引入的新特性,使函数组件也能使用 state 和其他 React 特性。

useState

import { useState } from 'react';function Counter() {const [count, setCount] = useState(0);return (<div><p>You clicked {count} times</p><button onClick={() => setCount(count + 1)}>Click me</button></div>);
}

useEffect

用于在函数组件中执行副作用操作(例如数据获取、订阅、手动 DOM 操作)。

import { useState, useEffect } from 'react';function Clock() {const [date, setDate] = useState(new Date());useEffect(() => {const timerID = setInterval(() => setDate(new Date()), 1000);return () => clearInterval(timerID);}, []);return <h2>It is {date.toLocaleTimeString()}.</h2>;
}

useContext

用于共享状态。

const MyContext = React.createContext();function MyProvider({ children }) {const [value, setValue] = useState('Hello, world!');return <MyContext.Provider value={value}>{children}</MyContext.Provider>;
}function MyComponent() {const value = useContext(MyContext);return <div>{value}</div>;
}

useReducer

用于管理复杂的 state 逻辑。

import { useReducer } from 'react';const initialState = { count: 0 };function reducer(state, action) {switch (action.type) {case 'increment':return { count: state.count + 1 };case 'decrement':return { count: state.count - 1 };default:throw new Error();}
}function Counter() {const [state, dispatch] = useReducer(reducer, initialState);return (<>Count: {state.count}<button onClick={() => dispatch({ type: 'increment' })}>+</button><button onClick={() => dispatch({ type: 'decrement' })}>-</button></>);
}

自定义 Hook

自定义 Hook 是提取组件逻辑复用的机制。

import { useState, useEffect } from 'react';function useFriendStatus(friendID) {const [isOnline, setIsOnline] = useState(null);useEffect(() => {function handleStatusChange(status) {setIsOnline(status.isOnline);}// 假设这里有一个订阅好友状态的 API// ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);return () => {// ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);};}, [friendID]);return isOnline;
}function FriendStatus(props) {const isOnline = useFriendStatus(props.friend.id);if (isOnline === null) {return 'Loading...';}return isOnline ? 'Online' : 'Offline';
}

4. Context API

Context 提供了一种在组件树中传递数据的方法,无需手动传递 props。

const ThemeContext = React.createContext('light');function App() {return (<ThemeContext.Provider value="dark"><Toolbar /></ThemeContext.Provider>);
}function Toolbar() {return (<div><ThemedButton /></div>);
}function ThemedButton() {const theme = useContext(ThemeContext);return <button theme={theme}>Themed Button</button>;
}

5. React Router

用于处理 React 应用的路由。

import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';function Home() {return <h2>Home</h2>;
}function About() {return <h2>About</h2>;
}function App() {return (<Router><div><nav><ul><li><Link to="/">Home</Link></li><li><Link to="/about">About</Link></li></ul></nav><Switch><Route path="/about"><About /></Route><Route path="/"><Home /></Route></Switch></div></Router>);
}

6. 状态管理

Redux

Redux 是一个用于管理应用状态的库。

import { createStore } from 'redux';
import { Provider, useDispatch, useSelector } from 'react-redux';const initialState = { count: 0 };function reducer(state = initialState, action) {switch (action.type) {case 'increment':return { count: state.count + 1 };case 'decrement':return { count: state.count - 1 };default:return state;}
}const store = createStore(reducer);function Counter() {const count = useSelector((state) => state.count);const dispatch = useDispatch();return (<><div>{count}</div><button onClick={() => dispatch({ type: 'increment' })}>+</button>

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

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

相关文章

DataBase 的一些规范 ?

1命名规范 1.1表名要有业务意义 1.2避免使用关键字 mysql关键字 1.3库、表、字段全部采用小写 1.4命名&#xff08;包括表名、列名&#xff09;禁止超过 30 个字符 1.5临时库、表名必须以 tmp 为前缀&#xff0c;并以日期为后缀&#xff1b;如&#xff1a;tmp_shop_info_2…

如何在Java中进行单元测试:JUnit 5的使用指南

如何在Java中进行单元测试&#xff1a;JUnit 5的使用指南 大家好&#xff0c;我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编&#xff0c;也是冬天不穿秋裤&#xff0c;天冷也要风度的程序猿&#xff01; 单元测试是软件开发中的一个关键环节&#xff0c;它…

贪心算法练习题(2024/6/18)

什么是贪心 贪心的本质是选择每一阶段的局部最优&#xff0c;从而达到全局最优。 贪心算法一般分为如下四步&#xff1a; 将问题分解为若干个子问题找出适合的贪心策略求解每一个子问题的最优解将局部最优解堆叠成全局最优解 1分发饼干 假设你是一位很棒的家长&#xff0c…

pytest测试框架pytest-rerunfailures插件重试失败用例

Pytest提供了丰富的插件来扩展其功能&#xff0c;介绍下插件pytest-rerunfailures &#xff0c;用于在测试用例失败时自动重新运行这些测试用例。 pytest-rerunfailures官方显示的python和pytest版本限制&#xff1a; Python 3.8pytest 7.2 或更新版本 此插件可以通过以下可…

Scala运算符及流程控制

Scala运算符及流程控制 文章目录 Scala运算符及流程控制写在前面运算符算数运算符关系运算符赋值运算符逻辑运算符位运算符运算符本质 流程控制分支控制单分支双分支多分支 循环控制for循环while循环循环中断嵌套循环 写在前面 操作系统&#xff1a;Windows10JDK版本&#xff…

1027. 方格取数

Powered by:NEFU AB-IN Link 文章目录 1027. 方格取数题意思路代码 1027. 方格取数 题意 某人从图中的左上角 A 出发&#xff0c;可以向下行走&#xff0c;也可以向右行走&#xff0c;直到到达右下角的 B 点。 在走过的路上&#xff0c;他可以取走方格中的数&#xff08;取…

ESP32-C3模组上跑通NVS(7)

接前一篇文章:ESP32-C3模组上跑通NVS(6) 上一回讲到乐鑫技术支持发来了操作自定义NVS分区的代码。本回就对于代码进行详细解析,并通过此过程看一下具体应如何进行正确的操作。下边就开始代码分析: 主函数 主函数即app_main()代码如下: void app_main(void) {esp_err_t…

FOC方案大合集!

获取链接&#xff01;&#xff01;&#xff01; 本次小编给大家带来了一份FOC的方案大合集。此套方案是基于峰岹科技FU68系列MCU的系列方案&#xff0c;包含常用的无感&#xff0c;有感无刷电机的应用&#xff0c;每份方案都包含了原理图&#xff0c;PCB&#xff0c;代码文件&…

【TOOL】ceres学习笔记(一) —— 教程练习

文章目录 一、Ceres Solver 介绍二、Ceres 使用基本步骤1. 构建最小二乘问题2. 求解最小二乘问题 三、使用案例1. Ceres Helloworld2. Powell’s Function3. Curve Fitting4. Robust Curve Fitting 一、Ceres Solver 介绍 Ceres-solver 是由Google开发的开源C库&#xff0c;用…

2024年P气瓶充装证模拟考试题库及P气瓶充装理论考试试题

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 2024年P气瓶充装证模拟考试题库及P气瓶充装理论考试试题是由安全生产模拟考试一点通提供&#xff0c;P气瓶充装证模拟考试题库是根据P气瓶充装最新版教材&#xff0c;P气瓶充装大纲整理而成&#xff08;含2024年P气瓶…

[Open-source tool]Uptime-kuma的簡介和安裝於Ubuntu 22.04系統

[Uptime Kuma]How to Monitor Mqtt Broker and Send Status to Line Notify Uptime-kuma 是一個基於Node.js的開軟軟體&#xff0c;同時也是一套應用於網路監控的開源軟體&#xff0c;其利用瀏覽器呈現直觀的使用者介面&#xff0c;如圖一所示&#xff0c;其讓使用者可監控各種…

vue3父组件获取子组件的实例对象

一&#xff0c;ref 在父组件的模板里&#xff0c;对子组件的标签定义ref属性&#xff0c;并且设置属性值&#xff0c;在方法里获取ref()获取实例对象。 父组件&#xff1a; <template><div ><div>我是父组件</div><<SonCom ref"sonComRe…

Oracle中生僻汉字的解决办法

在Oracle数据库中处理生僻汉字时&#xff0c;主要面临的问题是某些字符集可能无法完全支持所有的汉字&#xff0c;特别是生僻字。以下是一些解决Oracle中生僻汉字问题的办法&#xff1a; 检查当前字符集&#xff1a; 使用SELECT USERENV(language) FROM dual;命令来查看当前数…

jlink使用记录

https://www.eet-china.com/mp/a79854.html Jlink使用技巧之读取STM32内部的程序stm32芯片解除写保护方法&#xff08;详细&#xff09;_stm32进入写保护如何用segger恢复-CSDN博客 stm32芯片解除写保护方法&#xff08;详细&#xff09; keil程序和jlink两种ccs使用Jlink调试时…

足底筋膜炎的症状

足底筋膜炎是足底的肌腱或者筋膜发生无菌性炎症所致&#xff0c;其症状主要包括&#xff1a; 1、疼痛&#xff1a;这是足底筋膜炎最常见和突出的症状。疼痛通常出现在足跟或足底近足跟处&#xff0c;有时压痛较剧烈且持续存在。晨起时或长时间不活动后&#xff0c;疼痛感觉尤为…

从0到1 Python基础

从0到1 Python基础 文章目录 从0到1 Python基础语法基础流程控制列表与元组字符串字典与集合初始函数**数学计算**日期时间 语法基础 变量&#xff1a;一个可以改变的量 &#xff08;1&#xff09; 变量的命名规则&#xff1a;变量由字母、数字与下划线组成&#xff1b;第一个字…

高通安卓12-安卓系统定制2

将开机动画打包到system.img里面 在目录device->qcom下面 有lito和qssi两个文件夹 现在通过QSSI的方式创建开机动画&#xff0c;LITO方式是一样的 首先加入自己的开机动画&#xff0c;制作过程看前面的部分 打开qssi.mk文件&#xff0c;在文件的最后加入内容 PRODUCT_CO…

Python | Leetcode Python题解之第174题地下城游戏

题目&#xff1a; 题解&#xff1a; class Solution:def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:n, m len(dungeon), len(dungeon[0])BIG 10**9dp [[BIG] * (m 1) for _ in range(n 1)]dp[n][m - 1] dp[n - 1][m] 1for i in range(n - 1, -1, …

一文读懂LLM API应用开发基础(万字长文)

前言 Hello&#xff0c;大家好&#xff0c;我是GISer Liu&#x1f601;&#xff0c;一名热爱AI技术的GIS开发者&#xff0c;上一篇文章中我们详细介绍了LLM开发的基本概念&#xff0c;包括LLM的模型、特点能力以及应用&#xff1b;&#x1f632; 在本文中作者将通过&#xff1a…

Redis—Set数据类型及其常用命令详解

文章目录 一、Redis概述Set类型1 SADD:向集合&#xff08;Set&#xff09;中添加一个或多个成员2 SCARD:获取集合&#xff08;Set&#xff09;中成员数量3 SDIFF:获取多个集合之间的差集4 SDIFFSTORE:计算多个集合之间的差集&#xff0c;并将结果存储在指定的目标集合中5 SMEMB…