70 phút
State và Events trong React
useState Hook
Import useState
import React, { useState } from 'react';
Sử dụng useState
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Event Handling
Xử lý sự kiện cơ bản
function Button() {
const handleClick = () => {
alert('Button clicked!');
};
return <button onClick={handleClick}>Click me</button>;
}
Event Object
function Input() {
const handleChange = (event) => {
console.log(event.target.value);
};
return <input onChange={handleChange} />;
}
Form Handling
Controlled Component
function LoginForm() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
console.log('Login:', { username, password });
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Username"
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
/>
<button type="submit">Login</button>
</form>
);
}
Multiple State Variables
function UserProfile() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [age, setAge] = useState(0);
return (
<div>
<input value={name} onChange={(e) => setName(e.target.value)} />
<input value={email} onChange={(e) => setEmail(e.target.value)} />
<input
type="number"
value={age}
onChange={(e) => setAge(parseInt(e.target.value))}
/>
</div>
);
}
Bài tập thực hành
Hãy tạo một ứng dụng Todo List đơn giản!