React 是一个用于构建用户界面的 JavaScript 库,由 Facebook 开发并开源。
核心特性:
graph TB
A[React 核心原则] --> B[单一数据源<br/>Single Source of Truth]
A --> C[单向数据流<br/>Unidirectional Data Flow]
A --> D[声明式编程<br/>Declarative Programming]
A --> E[组件化<br/>Component-Based Architecture]
A --> F[学习曲线平缓<br/>Smooth Learning Curve]
style A fill:#f96
style B fill:#6f6
style C fill:#69f
style D fill:#96f9
style E fill:#69f9
style F fill:#6f6
// 1. 基本 JSX 示例
import React from 'react';
function App() {
// 返回 JSX
return (
<div className="app-container">
<h1>Hello, React!</h1>
<p>Welcome to React learning journey.</p>
<button onClick={handleClick}>
Click me
</button>
</div>
);
}
// 2. 条件渲染
const messages = ['Hello', 'World', 'React'];
function MessageList() {
return (
<div>
{messages.map((msg, index) => (
<div key={index}>
<h2>{msg}</h2>
</div>
))}
</div>
);
}
// 3. 属性展开
const user = {
name: 'John',
age: 30,
city: 'Shanghai'
};
function UserCard() {
return (
<div className="user-card">
<h3>{user.name}</h3>
<p>Age: {user.age}</p>
<p>City: {user.city}</p>
</div>
);
}
// 4. Fragment(避免额外包裹)
function Form() {
return (
<form>
<input type="text" placeholder="Username" />
<input type="password" placeholder="Password" />
<button type="submit">Submit</button>
</form>
);
}
JSX 语法与 Babel 对比:
| 特性 | JSX | Babel |
|---|---|---|
| 组件大小写 | 首字母 | 首字母 |
| 注入语法 | {var} |
this.var = value |
| 样式引入 | import |
import ... |
| Fragment | <>...</> |
<>...</> |
| 特殊属性 | className |
className |
import React from 'react';
// 1. 文本内容
function TextElement() {
const content = "This is a text node";
return<p>{content}</p>;
}
// 2. 数字/布尔渲染
function BooleanAndNumber() {
const count = 0;
const isVisible = true;
const numbers = [1, 2, 3, 4, 5];
return (
<div>
<p>Count: {count}</p>
<p>Is visible: {isVisible.toString()}</p>
<ul>
{numbers.map(num => (
<li key={num}>{num}</li>
))}
</ul>
</div>
);
}
// 3. 条件渲染(三元表达式)
function ConditionalRender() {
const isLoggedIn = true;
const userName = 'John';
return (
<div>
<h2>
{isLoggedIn ? `Welcome,${userName}!` : 'Please login'}
</h2>
{isLoggedIn && (
<p>You have access to premium content.</p>
)}
</div>
);
}
import React from 'react';
function TodoList() {
const todos = [
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Understand Hooks' },
{ id: 3, text: 'Build Components' }
];
// 使用 key �助 React 识别元素
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
{todo.text}
<button onClick={() => deleteTodo(todo.id)}>
Delete
</button>
</li>
))}
</ul>
);
}
function deleteTodo(id) {
console.log('Deleting todo:', id);
}
为什么需要 Key?
graph LR
A["初始状态<br/>render<br/节点1,2,3]"] --> B["重新排序<br/>节点1→3,2"]
B --> C["React 无法识别"]
C --> D["全量重新创建 DOM<br/>性能问题"]
style A fill:#f96
style D fill:#f96
| 场景 | 无 Key | 有 Key |
|---|---|---|
| 列表增加项 | React 无法识别,全量渲染 | 只创建新节点 |
| 列表排序 | 需要销毁重建 DOM | 高效排序 |
| 列表删除 | 从中间删除节点 | 从中间删除节点 |