Skip to content

Basic Component ใน React

Basic Component คืออะไร?

Basic Component คือคอมโพเนนต์พื้นฐานใน React ที่ใช้แสดง UI หนึ่งส่วน โดยมักจะรับข้อมูลผ่าน props และแสดงผลลัพธ์ออกมา สามารถนำไปประกอบกันเป็น UI ที่ซับซ้อนได้ในภายหลัง


ตัวอย่างการสร้าง Basic Component (Function Component)

tsx
// Greeting.tsx
export default function Greeting({ name, age }: { name: string; age: number }) {
  return <p>สวัสดี {name} อายุ {age} ปี</p>;
}

การใช้งานใน App

tsx
import Greeting from "./Greeting";

function App() {
  return <Greeting name="Aom" age={24} />;
}

การรับ props และการ render ข้อมูล

  • รับ props ผ่าน argument ของ function (destructuring ได้)
  • สามารถใช้ props เพื่อปรับเปลี่ยน UI ได้ตามต้องการ
tsx
function Welcome({ name }: { name: string }) {
  return <h1>ยินดีต้อนรับ {name}</h1>;
}

เปรียบเทียบกับแนวทางเก่า (Class Component)

tsx
import React from "react";

type GreetingProps = {
  name: string;
  age: number;
};

class Greeting extends React.Component<GreetingProps> {
  render() {
    return <p>สวัสดี {this.props.name} อายุ {this.props.age} ปี</p>;
  }
}

ตารางเปรียบเทียบ

ประเด็นFunction ComponentClass Component
Syntaxฟังก์ชันธรรมดาextends React.Component
รับ propsผ่าน argumentผ่าน this.props
State & Lifecycleใช้ React Hooksใช้ this.state, lifecycle methods
ความกระชับกระชับกว่าโค้ดยาวกว่า
แนะนำโดย React✅ (ปัจจุบัน)❌ (เลิกแนะนำ)

ข้อดีของการใช้ Function Component

  • โค้ดกระชับ อ่านง่าย ดูแลง่าย
  • ใช้ React Hooks ได้ (เช่น useState, useEffect)
  • Performance ดีกว่าเล็กน้อย (ไม่มี this)
  • เหมาะกับ React สมัยใหม่และ TypeScript

สรุปแนวทางที่แนะนำ

  • ใช้ Function Component เป็นหลักสำหรับการสร้าง UI ใน React
  • รับ props ผ่าน argument ของ function
  • ถ้าเริ่มต้นใหม่ ให้ใช้ TypeScript เพื่อความปลอดภัยของ type
  • หลีกเลี่ยงการใช้ Class Component ในโปรเจกต์ใหม่

การเข้าใจ Basic Component คือจุดเริ่มต้นสำคัญของการเขียน React ที่ดี ฝึกสร้างคอมโพเนนต์เล็กๆ หลายๆ แบบ จะช่วยให้เข้าใจแนวคิดนี้อย่างลึกซึ้งและต่อยอดไปสู่ Advanced Component ได้ง่ายขึ้น