Props (Properties) คือพร็อพเพอร์ตีที่ช่วยปรับแต่งคอมโพเนนท์ React คอมโพเนนท์ที่สร้างขึ้นสามารถใช้กับพารามิเตอร์ที่แตกต่างกันได้ด้วยแนวคิด props ด้วย props คุณสามารถส่งข้อมูลจากคอมโพเนนท์หนึ่งไปยังอีกคอมโพเนนท์หนึ่ง และนำคอมโพเนนท์ไปใช้ซ้ำตามต้องการ
คุณจะคุ้นเคยกับ props หากคุ้นเคยกับ ReactJS แนวคิดเดียวกันใช้ได้ใน React Native
มาดูตัวอย่างที่อธิบาย props:
ตัวอย่าง 1: Props ภายใน Built-in Components ของ React Native
พิจารณาคอมโพเนนท์ Image:
style และ source คือพร็อพเพอร์ตี (props) ของคอมโพเนนท์ Image style ใช้เพื่อเพิ่มสไตล์ เช่น width, height และ source ใช้กำหนด URL ของรูปภาพ เพื่อแสดงให้ผู้ใช้เห็น source และ style เป็น built-in props ของ Image component
สามารถใช้ตัวแปรที่เก็บ URL และนำไปใช้กับ props source:
let imgURI = {
uri: 'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png'
};
return (
);
ตัวอย่างด้านล่างแสดงการแสดงรูปภาพง่ายๆ ด้วย built-in props:
import React from "react";
import { Image, Text, View, StyleSheet } from "react-native";
const MyImage = () => {
let imgURI = {
uri: 'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png'
};
return (
);
}
const styles = StyleSheet.create({
container: {
paddingTop: 50,
paddingLeft: 50,
},
stretch: {
width: 200,
height: 200,
resizeMode: 'stretch',
}
});
export default MyImage;
ตัวอย่าง 2: Props ภายใน Custom Component
สามารถใช้ props ส่งข้อมูลจากคอมโพเนนท์หนึ่งไปอีกคอมโพเนนท์หนึ่ง ในตัวอย่างมี custom components 2 ตัวคือ Student และ Subject
คอมโพเนนท์ Subject:
const Subject = (props) => {
return (
I am studying - {props.name}!
);
}
คอมโพเนนท์รับพารามิเตอร์ props ใช้ภายใน Text component แสดงชื่อเป็น props.name มาดูวิธีส่ง props ให้ Subject จาก Student Component
คอมโพเนนท์ Student:
const Student = () => {
return (
);
}
ใน Student component ใช้ Subject component พร้อม props name ค่าที่ส่งคือ Maths, Physics, Chemistry Subject สามารถนำกลับมาใช้ซ้ำได้โดยส่งค่าต่างๆ ให้ props name
ตัวอย่างทำงานพร้อม Student และ Subject component:
import React from 'react';
import { Text, View } from 'react-native';
const Subject = (props) => {
return (
I am studying - {props.name}!
);
}
const Student = () => {
return (
);
}
export default Student;
ผลลัพธ์
