00 - React 基础

2024-06-24 12:12

本文主要是介绍00 - React 基础,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. React 基础

安装react指令

可参考:

  • 官网
  • 官网使用教程

如:

npx create-react-app 项目名
如:npx create-react-app react-redux-pro

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>

这篇关于00 - React 基础的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1090115

相关文章

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程

CSS3中的字体及相关属性详解

《CSS3中的字体及相关属性详解》:本文主要介绍了CSS3中的字体及相关属性,详细内容请阅读本文,希望能对你有所帮助... 字体网页字体的三个来源:用户机器上安装的字体,放心使用。保存在第三方网站上的字体,例如Typekit和Google,可以link标签链接到你的页面上。保存在你自己Web服务器上的字

从基础到进阶详解Pandas时间数据处理指南

《从基础到进阶详解Pandas时间数据处理指南》Pandas构建了完整的时间数据处理生态,核心由四个基础类构成,Timestamp,DatetimeIndex,Period和Timedelta,下面我... 目录1. 时间数据类型与基础操作1.1 核心时间对象体系1.2 时间数据生成技巧2. 时间索引与数据

html 滚动条滚动过快会留下边框线的解决方案

《html滚动条滚动过快会留下边框线的解决方案》:本文主要介绍了html滚动条滚动过快会留下边框线的解决方案,解决方法很简单,详细内容请阅读本文,希望能对你有所帮助... 滚动条滚动过快时,会留下边框线但其实大部分时候是这样的,没有多出边框线的滚动条滚动过快时留下边框线的问题通常与滚动条样式和滚动行

安装centos8设置基础软件仓库时出错的解决方案

《安装centos8设置基础软件仓库时出错的解决方案》:本文主要介绍安装centos8设置基础软件仓库时出错的解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录安装Centos8设置基础软件仓库时出错版本 8版本 8.2.200android4版本 javas

使用vscode搭建pywebview集成vue项目实践

《使用vscode搭建pywebview集成vue项目实践》:本文主要介绍使用vscode搭建pywebview集成vue项目实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录环境准备项目源码下载项目说明调试与生成可执行文件核心代码说明总结本节我们使用pythonpywebv

Linux基础命令@grep、wc、管道符的使用详解

《Linux基础命令@grep、wc、管道符的使用详解》:本文主要介绍Linux基础命令@grep、wc、管道符的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录grep概念语法作用演示一演示二演示三,带选项 -nwc概念语法作用wc,不带选项-c,统计字节数-

python操作redis基础

《python操作redis基础》Redis(RemoteDictionaryServer)是一个开源的、基于内存的键值对(Key-Value)存储系统,它通常用作数据库、缓存和消息代理,这篇文章... 目录1. Redis 简介2. 前提条件3. 安装 python Redis 客户端库4. 连接到 Re

使用Python和Tkinter实现html标签去除工具

《使用Python和Tkinter实现html标签去除工具》本文介绍用Python和Tkinter开发的HTML标签去除工具,支持去除HTML标签、转义实体并输出纯文本,提供图形界面操作及复制功能,需... 目录html 标签去除工具功能介绍创作过程1. 技术选型2. 核心实现逻辑3. 用户体验增强如何运行