Props
Props: ส่งข้อมูลระหว่าง Component
Section titled “Props: ส่งข้อมูลระหว่าง Component”Props คืออะไร?
Section titled “Props คืออะไร?”Props ย่อมาจาก “properties” — คือ arguments ที่ส่งเข้า component
ส่ง Props
Section titled “ส่ง Props”// Parent componentfunction App() { return <Greeting name="Somchai" />}
// Child component (รับ props เป็น parameter)function Greeting({ name }: { name: string }) { return <h1>สวัสดีครับ {name}!</h1>}Multiple Props
Section titled “Multiple Props”function UserCard({ name, age, city }: { name: string; age: number; city: string }) { return ( <div className="card"> <h2>{name}</h2> <p>อายุ: {age}</p> <p>เมือง: {city}</p> </div> )}
// ใช้งาน<UserCard name="Somchai" age={25} city="กรุงเทพ" />Default Props
Section titled “Default Props”function Badge({ text = "New", color = "blue" }: { text?: string; color?: string }) { return <span className={`badge badge-${color}`}>{text}</span>}
// <Badge /> → <span class="badge badge-blue">New</span>// <Badge text="Sale" /> → <span class="badge badge-blue">Sale</span>Callback Props
Section titled “Callback Props”เราสามารถส่ง function เป็น props เพื่อให้ child component สื่อสารกลับไปยัง parent ได้
// Parent componentfunction App() { const handleDelete = (id: number) => { console.log("ลบไอดี:", id) }
return <DeleteButton onDelete={handleDelete} />}
// Child component (รับ function เป็น props)function DeleteButton({ onDelete }: { onDelete: (id: number) => void }) { return <button onClick={() => onDelete(1)}>ลบ</button>}import { useState } from "react"
// ตัวอย่าง: Form ที่ส่ง state กลับไปยัง parentfunction LoginForm({ onSubmit }: { onSubmit: (data: { email: string; password: string }) => void }) { const [email, setEmail] = useState("") const [password, setPassword] = useState("")
const handleSubmit = () => { onSubmit({ email, password }) }
return ( <form onSubmit={handleSubmit}> <input 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> )} ลองส่ง callback function ผ่าน props ดูนะ จะได้เห็นว่า child สื่อสารกลับกับ parent ได้ยังไง
Quiz: Props พื้นฐาน
ข้อ 1 / 50%