본문으로 건너뛰기

เนื้อหาภาษาไทย / 태국어 콘텐츠

시스템 가이드 검수 완료된 콘텐츠

StyleSheet: ตกแต่ง Component ให้สวยงาม

บทนี้กล่าวถึงการใช้ `StyleSheet` ใน React Native เพื่อตกแต่ง Component ให้สวยงามและเป็นระเบียบ โดยเน้นข้อดีของการใช้ `StyleSheet` เช่น ความสะอาดของโค้ด, การนำ S...

StyleSheet: ตกแต่ง Component ให้สวยงาม

สวัสดีครับ! กลับมาพบกันอีกครั้งในบทเรียน React Native ฉบับเริ่มต้น สำหรับบทนี้ เราจะมาเรียนรู้เกี่ยวกับการใช้ StyleSheet เพื่อตกแต่ง Component ของเราให้สวยงามและน่าใช้งานมากยิ่งขึ้น ในบทที่แล้ว เราได้เรียนรู้เรื่อง State ซึ่งเป็นข้อมูลภายใน Component ที่สามารถเปลี่ยนแปลงได้ และส่งผลต่อการแสดงผลของ UI ในบทนี้ เราจะมาดูวิธีการจัดการกับรูปลักษณ์ภายนอกของ Component กันบ้างครับ

ทำไมต้องใช้ StyleSheet?

ก่อนที่เราจะเริ่มลงมือเขียนโค้ด เรามาทำความเข้าใจกันก่อนว่าทำไมเราถึงต้องใช้ StyleSheet ใน React Native แทนที่จะเขียน Style ไปตรงๆ ใน Component เลย เหตุผลหลักๆ มีดังนี้:

  • ความสะอาดของ Code: การใช้ StyleSheet ช่วยให้ Code ของเราเป็นระเบียบและอ่านง่ายขึ้น เราสามารถแยกส่วนของการกำหนด Style ออกจากส่วนของการจัดการ Logic ของ Component ได้อย่างชัดเจน
  • Reusable Style: เราสามารถสร้าง Style ที่สามารถนำไปใช้ซ้ำในหลายๆ Component ได้ ซึ่งช่วยลดความซ้ำซ้อนของ Code และทำให้การแก้ไข Style เป็นไปได้ง่ายขึ้น
  • Performance: React Native ได้รับการออกแบบมาให้ StyleSheet มีประสิทธิภาพที่ดีกว่าการใช้ Inline Style ในบางกรณี โดยเฉพาะอย่างยิ่งเมื่อมีการใช้ Style ที่ซับซ้อน

การสร้าง StyleSheet

การสร้าง StyleSheet ใน React Native นั้นง่ายมาก เราใช้ Function StyleSheet.create() เพื่อสร้าง Object ที่เก็บ Style ต่างๆ ของเรา ตัวอย่างเช่น:

import { StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    fontSize: 20,
    fontWeight: 'bold',
    color: 'blue',
  },
});

export default styles;

จากตัวอย่างข้างต้น เราได้สร้าง StyleSheet ที่ชื่อว่า styles ซึ่งมี Style อยู่ 2 แบบคือ container และ text แต่ละ Style เป็น Object ที่มี Property ต่างๆ ที่กำหนดรูปลักษณ์ของ Component เช่น flex, backgroundColor, fontSize, fontWeight และ color

คำอธิบาย Property ที่ใช้บ่อย:

  • flex: กำหนดสัดส่วนของพื้นที่ที่ Component จะใช้ใน Container (คล้ายๆ Flexbox ใน CSS)
  • backgroundColor: กำหนดสีพื้นหลัง
  • alignItems: กำหนดการจัดเรียงตามแกนแนวขวาง (Horizontal)
  • justifyContent: กำหนดการจัดเรียงตามแกนแนวตั้ง (Vertical)
  • fontSize: กำหนดขนาดตัวอักษร
  • fontWeight: กำหนดความหนาของตัวอักษร (เช่น 'bold', 'normal')
  • color: กำหนดสีตัวอักษร
  • margin, padding: กำหนดระยะห่างรอบนอกและภายใน Component
  • width, height: กำหนดความกว้างและความสูงของ Component
  • borderRadius: กำหนดความโค้งมนของมุม
  • borderWidth, borderColor: กำหนดความหนาและสีของเส้นขอบ

การกำหนด Style ให้กับ Component

เมื่อเราสร้าง StyleSheet แล้ว เราสามารถนำ Style เหล่านั้นไปใช้กับ Component ของเราได้ โดยใช้ Property style ตัวอย่างเช่น:

import React from 'react';
import { View, Text } from 'react-native';
import styles from './styles'; // Import StyleSheet ที่เราสร้างไว้

const MyComponent = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>Hello, World!</Text>
    </View>
  );
};

export default MyComponent;

ในตัวอย่างนี้ เราได้ Import StyleSheet ที่ชื่อว่า styles เข้ามา และนำ Style container ไปใช้กับ View Component และ Style text ไปใช้กับ Text Component โดยใช้ styles.container และ styles.text ตามลำดับ

การใช้ Inline Style vs. StyleSheet

นอกจาก StyleSheet แล้ว เรายังสามารถกำหนด Style ให้กับ Component ได้โดยตรงโดยใช้ Inline Style ซึ่งเป็นการเขียน Style ลงไปใน Property style ของ Component เลย ตัวอย่างเช่น:

import React from 'react';
import { View, Text } from 'react-native';

const MyComponent = () => {
  return (
    <View style={{ flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center' }}>
      <Text style={{ fontSize: 20, fontWeight: 'bold', color: 'blue' }}>Hello, World!</Text>
    </View>
  );
};

export default MyComponent;

ถึงแม้ว่าการใช้ Inline Style จะสะดวกและรวดเร็ว แต่ก็มีข้อเสียหลายอย่างเมื่อเทียบกับการใช้ StyleSheet ดังที่กล่าวไปแล้วข้างต้น ดังนั้น โดยทั่วไปแล้ว เราจึงแนะนำให้ใช้ StyleSheet มากกว่า Inline Style ยกเว้นในกรณีที่ต้องการกำหนด Style ที่เฉพาะเจาะจงสำหรับ Component นั้นๆ เท่านั้น หรือต้องการเปลี่ยนแปลง Style แบบ Dynamic ตามเงื่อนไขบางอย่าง

การรวม Style หลายๆ แบบ

บางครั้ง เราอาจต้องการรวม Style หลายๆ แบบเข้าด้วยกัน เช่น ต้องการใช้ Style ที่กำหนดไว้ใน StyleSheet ร่วมกับ Inline Style หรือต้องการรวม Style จาก StyleSheet หลายๆ ตัว เราสามารถทำได้โดยการส่ง Array ของ Style Object ไปยัง Property style ตัวอย่างเช่น:

import React from 'react';
import { View, Text } from 'react-native';
import styles from './styles';

const MyComponent = () => {
  return (
    <View style={[styles.container, { padding: 20 }]}>
      <Text style={[styles.text, { textDecorationLine: 'underline' }]}>Hello, World!</Text>
    </View>
  );
};

export default MyComponent;

ในตัวอย่างนี้ เราได้รวม Style container จาก StyleSheet เข้ากับ Inline Style { padding: 20 } และรวม Style text จาก StyleSheet เข้ากับ Inline Style { textDecorationLine: 'underline' } โดยการส่ง Array [styles.container, { padding: 20 }] และ [styles.text, { textDecorationLine: 'underline' }] ไปยัง Property style ตามลำดับ

การใช้ Dynamic Style

ในบางสถานการณ์ เราอาจต้องการเปลี่ยนแปลง Style ของ Component แบบ Dynamic ตามเงื่อนไขบางอย่าง เช่น ต้องการเปลี่ยนสีพื้นหลังของปุ่มเมื่อผู้ใช้กดปุ่ม เราสามารถทำได้โดยการใช้ State ร่วมกับ StyleSheet หรือ Inline Style ตัวอย่างเช่น:

import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';

const MyComponent = () => {
  const [isPressed, setIsPressed] = useState(false);

  const handlePress = () => {
    setIsPressed(!isPressed);
  };

  const buttonStyle = [
    styles.button,
    isPressed ? styles.buttonPressed : null, // Conditional Styling
  ];

  return (
    <TouchableOpacity style={buttonStyle} onPress={handlePress}>
      <Text style={styles.buttonText}>Press Me</Text>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  button: {
    backgroundColor: 'lightblue',
    padding: 10,
    borderRadius: 5,
  },
  buttonPressed: {
    backgroundColor: 'darkblue',
  },
  buttonText: {
    color: 'white',
    fontWeight: 'bold',
  },
});

export default MyComponent;

ในตัวอย่างนี้ เราใช้ useState Hook เพื่อสร้าง State ที่ชื่อว่า isPressed ซึ่งเก็บค่าว่าปุ่มถูกกดหรือไม่ เมื่อผู้ใช้กดปุ่ม Function handlePress จะถูกเรียกใช้ และจะทำการ Toggle ค่าของ isPressed จากนั้น เราได้สร้าง buttonStyle ซึ่งเป็น Array ที่รวม Style button จาก StyleSheet เข้ากับ Style buttonPressed (ถ้า isPressed เป็น true) โดยใช้ Conditional Styling

สรุป

ในบทนี้ เราได้เรียนรู้เกี่ยวกับการใช้ StyleSheet เพื่อตกแต่ง Component ใน React Native ซึ่งช่วยให้ Code ของเราเป็นระเบียบ อ่านง่าย และมีประสิทธิภาพมากยิ่งขึ้น เราได้เรียนรู้ถึงวิธีการสร้าง StyleSheet, การกำหนด Style ให้กับ Component, การใช้ Inline Style vs. StyleSheet, การรวม Style หลายๆ แบบ และการใช้ Dynamic Style

ในบทต่อไป เราจะมาเรียนรู้เกี่ยวกับการใช้งาน TextInput เพื่อรับข้อมูลจากผู้ใช้ อย่าลืมติดตามกันนะครับ!

Office.in.th Custom Service

이 구조를 바탕으로 시스템을 개발하거나 맞춤 변경하고 싶으신가요?

Office.in.th는 엔터프라이즈 웹 애플리케이션, API 연동, 공공/민간 업무 관리 시스템을 설계·개발하며 장기 지원을 제공합니다.

소프트웨어 개발 서비스 보기