← Về danh sách bài họcBài 3/25
🧩 Bài 3: Components - Thành Phần Giao Diện
🎯 Sau bài học này, bạn sẽ:
- Hiểu khái niệm Component trong React
- Tạo Function Components và Class Components
- Biết Component Composition (kết hợp components)
- Hiểu nguyên tắc chia nhỏ UI thành components
1. Component Là Gì?
Component là khối xây dựng cơ bản của React. Mỗi component là một phần giao diện độc lập, có thể tái sử dụng. Giống như LEGO — bạn ghép các khối nhỏ lại thành ứng dụng hoàn chỉnh.
📌 Nguyên tắc: Mỗi component nên làm một việc duy nhất (Single Responsibility Principle). Nếu component quá phức tạp, hãy chia nhỏ nó.
2. Function Component (Khuyên dùng)
Từ React 16.8+ với Hooks, function component là cách viết chính:
// Component đơn giản
function Welcome() {
return <h1>Chào mừng đến với React!</h1>;
}
// Arrow function (phổ biến)
const Greeting = ({ name }) => {
return <p>Xin chào, {name}!</p>;
};
// Component phức tạp hơn
function UserCard({ user }) {
return (
<div className="user-card">
<img src={user.avatar} alt={user.name} />
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
);
}
// Sử dụng
function App() {
const user = { name: 'An', email: '[email protected]', avatar: '/an.jpg' };
return (
<div>
<Welcome />
<Greeting name="Bình" />
<UserCard user={user} />
</div>
);
}
3. Class Component (Legacy)
Cách viết cũ, vẫn gặp trong code legacy:
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState(prev => ({ count: prev.count + 1 }));
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>+1</button>
</div>
);
}
}
⚠️ Lưu ý: Class components vẫn hoạt động nhưng không còn được khuyên dùng. React team khuyến khích dùng function components + hooks cho tất cả code mới.
4. Component Composition
// Chia nhỏ UI thành các component
function Header() {
return <header><h1>My App</h1></header>;
}
function Sidebar({ items }) {
return (
<aside>
{items.map(item => (
<a key={item.id} href={item.url}>{item.label}</a>
))}
</aside>
);
}
function MainContent({ children }) {
return <main className="content">{children}</main>;
}
function Footer() {
return <footer><p>© 2024</p></footer>;
}
// Kết hợp lại
function App() {
const menuItems = [
{ id: 1, label: 'Home', url: '/' },
{ id: 2, label: 'About', url: '/about' }
];
return (
<div className="app">
<Header />
<div className="layout">
<Sidebar items={menuItems} />
<MainContent>
<h2>Nội dung chính</h2>
<p>Đây là trang chủ.</p>
</MainContent>
</div>
<Footer />
</div>
);
}
📝 Tóm Tắt
- Component = khối xây dựng UI, có thể tái sử dụng
- Function component là cách viết hiện đại (khuyên dùng)
- Class component là legacy, vẫn cần biết khi đọc code cũ
- Chia nhỏ UI theo Single Responsibility Principle
- Dùng composition để kết hợp components