Dark mode
การจัดการ Events ใน React
Event Handling พื้นฐาน
Event Handling ใน React ใช้ syntax ที่คล้ายกับ HTML แต่ใช้ camelCase และต้องส่งฟังก์ชันไปเป็น handler ไม่ใช่ string Event Handling ใน React ใช้ syntax ที่คล้ายกับ HTML แต่ใช้ camelCase และต้องส่งฟังก์ชันไปเป็น handler ไม่ใช่ string
tsx
function Button() {
const handleClick = () => {
console.log("Button clicked!");
};
return <button onClick={handleClick}>Click Me</button>;
}
Event Object
React มี Synthetic Event Object ที่ครอบ browser's native event ไว้ ทำให้ใช้งานได้สอดคล้องกันทุก browser React มี Synthetic Event Object ที่ครอบ browser's native event ไว้ ทำให้ใช้งานได้สอดคล้องกันทุก browser
tsx
function Input() {
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log("Value:", e.target.value);
};
return <input type="text" onChange={handleChange} />;
}
Form Handling
การจัดการ Form ใน React ใช้เทคนิค Controlled Components โดยผูกค่า input กับ state และใช้ onChange เพื่ออัปเดต state การจัดการ Form ใน React ใช้เทคนิค Controlled Components โดยผูกค่า input กับ state และใช้ onChange เพื่ออัปเดต state
tsx
function LoginForm() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
console.log({ email, password });
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Login</button>
</form>
);
}
Synthetic Events
Synthetic Events ใน React มี method เช่น stopPropagation() เพื่อควบคุมการไหลของ event และป้องกันพฤติกรรม default ของ browser Synthetic Events ใน React มี method เช่น stopPropagation() เพื่อควบคุมการไหลของ event และป้องกันพฤติกรรม default ของ browser
tsx
function List() {
const handleItemClick = (e: React.MouseEvent, id: number) => {
e.stopPropagation();
console.log("Item clicked:", id);
};
return (
<ul onClick={() => console.log("List clicked")}>
{[1, 2, 3].map((id) => (
<li
key={id}
onClick={(e) => handleItemClick(e, id)}
>
Item {id}
</li>
))}
</ul>
);
}
Custom Events
สามารถสร้าง Custom Events โดยส่งฟังก์ชัน callback ผ่าน props เพื่อให้ Child Component เรียกใช้งานเมื่อเกิดเหตุการณ์ต่างๆ สามารถสร้าง Custom Events โดยส่งฟังก์ชัน callback ผ่าน props เพื่อให้ Child Component เรียกใช้งานเมื่อเกิดเหตุการณ์ต่างๆ
tsx
function Child({ onAction }: { onAction: (data: string) => void }) {
return (
<button onClick={() => onAction("Hello from child")}>
Trigger Action
</button>
);
}
function Parent() {
const handleChildAction = (data: string) => {
console.log(data); // 'Hello from child'
};
return <Child onAction={handleChildAction} />;
}