React 是目前最流行的前端框架之一,其核心是组件化开发和虚拟 DOM。以下从基础语法到高级特性,为你提供系统化的学习路径和代码示例。
首先需要安装 Node.js(包含 npm 或 yarn),然后创建 React 项目:
# 使用 create-react-app 脚手架
npx create-react-app my-react-app
cd my-react-app
npm start # 启动开发服务器
React 组件分为函数组件和类组件,推荐使用函数组件(更简洁,配合 Hooks)。
// 函数组件(推荐)
const Welcome = (props) => {
return Hello, {props.name}
;
};
// 类组件(旧写法)
class Welcome extends React.Component {
render() {
return Hello, {this.props.name}
;
}
}
JSX 是 JavaScript 的语法扩展,用于描述 UI 结构:
const element = (
Hello, JSX!
{1 + 2}
{/* 嵌入表达式 */}
{true && 条件渲染
}
);
className
而非 class
![]()
){}
使用 useState
Hook 管理组件内部状态:
import { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0); // 初始化状态
return (
Count: {count}
);
};
useEffect
替代类组件的 componentDidMount
、componentDidUpdate
和 componentWillUnmount
:
import { useEffect, useState } from 'react';
const Example = () => {
const [data, setData] = useState(null);
useEffect(() => {
// 组件挂载后执行(类似 componentDidMount)
fetchData();
// 清理函数(类似 componentWillUnmount)
return () => {
// 资源清理逻辑
};
}, []); // 空依赖数组表示只执行一次
return {data};
};
// 父组件
const Parent = () => {
const [message, setMessage] = useState('');
const handleChildClick = (newMessage) => {
setMessage(newMessage);
};
return (
Received: {message}
);
};
// 子组件
const Child = (props) => {
return (
);
};
const UserGreeting = ({ isLoggedIn }) => {
return isLoggedIn ? (
Welcome back!
) : (
Please log in.
);
};
使用 .map()
方法渲染列表,注意添加唯一 key
:
const TodoList = ({ todos }) => {
return (
{todos.map(todo => (
- {todo.text}
))}
);
};
提取可复用的逻辑:
// useFetch.js
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => {
setData(data);
setLoading(false);
});
}, [url]);
return { data, loading };
};
// 使用自定义 Hook
const PostList = () => {
const { data, loading } = useFetch('https://api.example.com/posts');
if (loading) return Loading...
;
return {data.map(post => {post.title}
)};
};
跨层级传递数据(替代层层传递 props):
// 创建 Context
const ThemeContext = React.createContext();
// 提供者组件
const App = () => {
const theme = 'dark';
return (
);
};
// 深层组件使用
const Toolbar = () => {
return (
);
};
const ThemedButton = () => {
const theme = useContext(ThemeContext); // 使用 useContext Hook
return ;
};
需要我针对某个具体部分展开讲解或提供更多示例吗?