Skip to content

Props

Props: ส่งข้อมูลระหว่าง Component

Section titled “Props: ส่งข้อมูลระหว่าง Component”

Props ย่อมาจาก “properties” — คือ arguments ที่ส่งเข้า component

// Parent component
function App() {
return <Greeting name="Somchai" />
}
// Child component (รับ props เป็น parameter)
function Greeting({ name }: { name: string }) {
return <h1>สวัสดีครับ {name}!</h1>
}
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="กรุงเทพ" />
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>

เราสามารถส่ง function เป็น props เพื่อให้ child component สื่อสารกลับไปยัง parent ได้

// Parent component
function 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 กลับไปยัง parent
function 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>
)
}
Avatar whiteCat
ลองส่ง callback function ผ่าน props ดูนะ จะได้เห็นว่า child สื่อสารกลับกับ parent ได้ยังไง

Quiz: Props พื้นฐาน

ข้อ 1 / 50%

Props ย่อมาจากอะไร?