React 18 详细语法与方法
1. React 基础
(1)JSX 语法
JSX(JavaScript XML)是一种 类似 HTML 的 JavaScript 语法,用于描述 UI 结构。
1
| const element = <h1>Hello, React!</h1>;
|
📌 JSX 规则
-
必须返回一个单一根元素(可以使用 <></> 片段 Fragment 避免额外的 div)。
-
属性用 camelCase,例如 className 而不是 class。
-
JS 变量和表达式用 {} 包裹:
1 2
| const name = "Alice"; const element = <h1>Hello, {name}!</h1>;
|
-
三元表达式(if 语句不能直接在 JSX 里使用):
1 2
| const isLoggedIn = true; return <h1>{isLoggedIn ? "Welcome!" : "Please log in."}</h1>;
|
2. 组件
(1)函数组件(推荐)
1 2 3 4 5
| function Welcome(props) { return <h1>Hello, {props.name}!</h1>; }
export default Welcome;
|
(2)类组件(不推荐)
1 2 3 4 5 6 7 8 9
| import React, { Component } from 'react';
class Welcome extends Component { render() { return <h1>Hello, {this.props.name}!</h1>; } }
export default Welcome;
|
🚀 React 18 推荐使用函数组件,因为它支持 Hooks,代码更简洁。
3. Props(属性)
Props 用于 父组件向子组件传递数据,是 只读的。
1 2 3 4 5 6 7
| function User(props) { return <h1>Hello, {props.name}!</h1>; }
export default function App() { return <User name="Alice" />; }
|
📌 默认 Props
1 2 3
| User.defaultProps = { name: "Guest" };
|
📌 类型检查(使用 TypeScript)
1 2 3 4 5 6 7
| interface UserProps { name: string; }
function User({ name }: UserProps) { return <h1>Hello, {name}!</h1>; }
|
4. 事件处理
1 2 3 4 5
| function Button() { const handleClick = () => alert("按钮被点击了!");
return <button onClick={handleClick}>点我</button>; }
|
📌 事件传递参数
1
| <button onClick={(e) => handleClick(e, 'Hello')}>点我</button>
|
📌 阻止默认行为
1 2 3 4 5 6 7 8
| function Link() { const handleClick = (e) => { e.preventDefault(); alert("默认行为已阻止!"); };
return <a href="https://example.com" onClick={handleClick}>点击</a>; }
|
5. 组件状态(useState Hook)
📌 基本用法
1 2 3 4 5 6 7 8 9 10 11 12
| import { useState } from 'react';
function Counter() { const [count, setCount] = useState(0);
return ( <div> <p>计数: {count}</p> <button onClick={() => setCount(count + 1)}>增加</button> </div> ); }
|
📌 延迟状态更新
1
| setCount((prevCount) => prevCount + 1);
|
6. 副作用(useEffect Hook)
📌 组件加载时执行
1 2 3
| useEffect(() => { console.log("组件挂载完成"); }, []);
|
📌 监听 count 变化
1 2 3
| useEffect(() => { console.log("count 发生变化:", count); }, [count]);
|
📌 清理副作用
1 2 3 4 5 6 7
| useEffect(() => { const timer = setInterval(() => { console.log("定时器运行中..."); }, 1000);
return () => clearInterval(timer); }, []);
|
7. useContext(全局状态)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const ThemeContext = createContext("light");
function ThemeButton() { const theme = useContext(ThemeContext); return <button className={theme}>按钮</button>; }
export default function App() { return ( <ThemeContext.Provider value="dark"> <ThemeButton /> </ThemeContext.Provider> ); }
|
8. React Router(前端路由)
📌 安装
1
| yarn add react-router-dom
|
📌 使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
function Home() { return <h1>首页</h1>; }
function About() { return <h1>关于</h1>; }
export default function App() { return ( <BrowserRouter> <nav> <Link to="/">首页</Link> | <Link to="/about">关于</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </BrowserRouter> ); }
|
9. 全局状态管理(Redux & Zustand)
(1)Redux
📌 安装
1
| yarn add @reduxjs/toolkit react-redux
|
📌 定义 Store
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import { configureStore, createSlice } from '@reduxjs/toolkit'; import { Provider, useDispatch, useSelector } from 'react-redux';
const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment: (state) => { state.value += 1; } } });
const store = configureStore({ reducer: { counter: counterSlice.reducer } });
function Counter() { const count = useSelector(state => state.counter.value); const dispatch = useDispatch();
return ( <div> <p>Count: {count}</p> <button onClick={() => dispatch(counterSlice.actions.increment())}>增加</button> </div> ); }
export default function App() { return ( <Provider store={store}> <Counter /> </Provider> ); }
|
(2)Zustand(更轻量的状态管理)
📌 安装
📌 使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import create from 'zustand';
const useStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })) }));
function Counter() { const { count, increment } = useStore(); return ( <div> <p>Count: {count}</p> <button onClick={increment}>增加</button> </div> ); }
export default Counter;
|
📌 Zustand 比 Redux 更轻量,适用于小型应用。
总结
| 功能 |
方法 |
| 组件 |
function Component() |
| 事件 |
onClick={handleClick} |
| 状态 |
useState() |
| 副作用 |
useEffect() |
| 全局状态 |
useContext()、Redux、Zustand |
| 路由 |
react-router-dom |
| 性能优化 |
useMemo()、useCallback() |
这份 React 18 语法和方法大全 可以作为你的学习手册 🚀!
如果您喜欢此博客或发现它对您有用,则欢迎对此发表评论。 也欢迎您共享此博客,以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权,请与作者联系以将其删除。 谢谢 !