Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Props trong React Native là gì?


Props (properties) là các thuộc tính giúp tùy chỉnh component React. Component có thể tái sử dụng với các tham số khác nhau nhờ props. Props cho phép truyền dữ liệu từ component cha sang con và tái sử dụng component theo nhu cầu.

Nếu bạn quen với ReactJS, khái niệm props trong React Native hoàn toàn tương tự.

Ví dụ 1: Props trong Built-in Components

Xét component Image:

style và source là props của Image. style để định dạng (width, height), source để gán URL ảnh. Cũng có thể dùng biến:

let imgURI = {
    uri: 'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png'
};
return (
    
        
    
);

Ví dụ hoàn chỉnh hiển thị ảnh:

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;

Ví dụ 2: Props trong Custom Component

Truyền dữ liệu giữa component tùy chỉnh. Tạo component Subject nhận props:

const Subject = (props) => {
    return (
        
            
                I am studying - {props.name}!
            
        
    );
}

Component Student dùng Subject với props name khác nhau:

const Student = () => {
    return (
        
            
            
            
        
    );
}

Mã hoàn chỉnh:

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;

Kết quả

Props trong React Native là gì?