从概念到实践:构建高效可维护的UI
演讲者:[您的姓名/角色]
2024 年 5 月 27 日
React组件是构建用户界面的核心积木。它们是独立的、可复用的代码块,负责渲染UI的一部分。
在React Hooks出现之前,组件主要分为类组件和函数组件。Hooks的引入,使得函数组件拥有了状态和生命周期能力。
| 特性 | 函数组件 (React Hooks) | 类组件 |
|---|---|---|
| 语法 | 函数声明/表达式 | ES6 Class |
| 状态 (State) | 使用 `useState` Hook | 使用 `this.state` |
| 生命周期 | 使用 `useEffect` Hook (模拟) | 通过 `componentDidMount`, `componentDidUpdate` 等方法 |
| 性能 | 通常更易于优化 (如 `React.memo`) | 需要 `PureComponent` 或 `shouldComponentUpdate` |
| 代码量 | 通常更简洁 (逻辑复用更易) | Boilerplate 代码较多 |
React组件从挂载到卸载会经历不同阶段。函数组件通过 Hooks(如 `useState`, `useEffect`)来管理状态和模拟生命周期行为。
import React, { useState, useEffect } from 'react';
function Counter() {
// 1. useState: 声明状态变量
const [count, setCount] = useState(0);
// 2. useEffect: 模拟副作用(如组件挂载、更新、卸载)
useEffect(() => {
// 相当于 componentDidMount 和 componentDidUpdate
console.log(`Count has updated to: ${count}`);
// 返回一个清理函数,相当于 componentWillUnmount
return () => {
console.log('Component will unmount or effect re-runs cleanup');
};
}, [count]); // 依赖数组:只有当count变化时,effect才重新运行
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
数据是驱动React应用的核心。`props` 和 `state` 是React中两种最重要的数据类型,它们共同定义了组件的行为和外观。
React应用由多个组件构成,它们之间需要相互协作和传递数据。
// ParentComponent.js
function ParentComponent() {
const [message, setMessage] = useState('Hello from Parent!');
const handleChildClick = (data) => {
setMessage(`Child says: ${data}`);
};
return (
<div>
<h3>Parent: {message}</h3>
{/* 1. 父传子:通过 props 传递数据和回调函数 */}
<ChildComponent
greeting={message}
onChildAction={handleChildClick}
/>
</div>
);
}
// ChildComponent.js
function ChildComponent({ greeting, onChildAction }) {
return (
<div>
<p>Child received: {greeting}</p>
{/* 2. 子传父:调用父组件传入的回调函数 */}
<button onClick={() => onChildAction('I clicked!')}>
Click Me (Child)
</button>
</div>
);
}
优秀的React组件不仅功能完善,更应具备高复用性和易维护性。
// MyPureComponent.js
import React from 'react';
function MyComponent({ name, count }) {
console.log('MyComponent rendered');
return (
<div>
<p>Name: {name}</p>
<p>Count: {count}</p>
</div>
);
}
// 使用 React.memo 包装组件,只有当 props 发生变化时才重新渲染
// 这是一个“浅比较”
export default React.memo(MyComponent);
// Parent usage
function Parent() {
const [clicks, setClicks] = useState(0);
const user = { name: 'Alice' }; // Object reference changes on re-render
return (
<div>
<button onClick={() => setClicks(clicks + 1)}>
Click Parent ({clicks})
</button>
{/* 这里的MyPureComponent只有当props.count变化时才会重新渲染,因为props.name是一个原始值 */}
<MyPureComponent name="Bob" count={clicks} />
{/* 这里的MyPureComponent因为 user 对象每次都是新的引用,所以总是重新渲染 */}
<MyPureComponent name={user.name} count={clicks} />
</div>
);
}
深入学习更多高级Hooks,如 `useReducer`, `useContext`, `useCallback`, `useMemo`。
尝试构建一个小型React项目,将所学知识付诸实践。
探索状态管理库,如Redux Toolkit或Zustand,应对复杂数据流。
感谢聆听! Q&A
感谢您的宝贵时间!希望本次演示能帮助您更好地理解React组件开发。 如果您有任何问题,欢迎随时交流。
期待与您共同探索前端的未来!