JSX 语法
JSX是JavaScript的语法扩展,让你可以在JavaScript中编写类似HTML的代码
// JSX语法示例
function Welcome(props) {
// 这是一个React函数组件
// props是组件接收的属性(类似HTML元素的attributes)
return (
// JSX返回值必须用括号包裹,确保正确解析
<div className="welcome">
{/* 注意:JSX中使用className而不是class */}
<h1>Hello, {props.name}!</h1>
{/* 大括号{}内可以写JavaScript表达式 */}
<p>Welcome to React</p>
</div>
);
}
// 使用组件就像使用HTML标签一样简单
<Welcome name="张三" />
{/* name="张三"是传递给组件的props */}
组件化开发
React应用由组件构成,组件是可复用的UI单元,具有自己的状态和逻辑
// 函数组件(推荐的现代写法)
function Button({ text, onClick, type = 'primary' }) {
// 解构props:从传入的属性中提取需要的值
// type = 'primary':设置默认值
return (
<button
className={`btn btn-${type}`}
{/* 模板字符串:动态生成CSS类名 */}
onClick={onClick}
{/* 事件处理:接收父组件传递的点击函数 */}
>
{text}
{/* 显示按钮文字 */}
</button>
);
}
// 类组件(传统写法,了解即可)
class Counter extends React.Component {
constructor(props) {
super(props);
// 初始化组件状态
this.state = { count: 0 };
}
render() {
// render方法返回组件的UI结构
return (
<div>
<p>Count: {this.state.count}</p>
{/* 显示当前计数值 */}
<Button
text="增加"
onClick={() => this.setState({count: this.state.count + 1})}
{/* 使用自定义Button组件,体现组件复用 */}
/>
</div>
);
}
}
React Hooks
Hooks让你在函数组件中使用state和其他React特性,是现代React开发的核心
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
// useState Hook - 管理状态
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
// useEffect Hook - 处理副作用
useEffect(() => {
async function fetchUser() {
setLoading(true);
try {
const response = await fetch(`/api/users/${userId}`);
const userData = await response.json();
setUser(userData);
} catch (error) {
console.error('获取用户信息失败:', error);
} finally {
setLoading(false);
}
}
fetchUser();
}, [userId]); // 依赖数组
if (loading) return <div>加载中...</div>;
if (!user) return <div>用户不存在</div>;
return (
<div className="user-profile">
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
状态管理
React中的状态管理包括本地状态(useState)和全局状态(Context API、Redux等)
// 创建Context
const ThemeContext = React.createContext();
// Provider组件
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
// 使用Context
function ThemedButton() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button
className={`btn btn-${theme}`}
onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
>
切换到{theme === 'light' ? '深色' : '浅色'}主题
</button>
);
}
React 交互演示
下面是一个简单的React计数器演示,展示了状态管理和事件处理: