React Native 中的 props 是什麼?
Props 是屬性,有助於修改 React 元件。可以使用 props 概念建立具有不同引數的元件。透過 props,您可以將資訊從一個元件傳遞到另一個元件,同時根據您的需求重複使用元件。
如果您熟悉 ReactJS,那麼您將熟悉 props,React Native 中也遵循相同的概念。
讓我們來看一個解釋 props 的示例。
示例 1:React Native 內建元件中的 Props
考慮 Image 元件:
<Image style={styles.stretch} source={{uri: 'https://pbs.twimg.com/profile_images/486929358120964097 /gNLINY67_400x400.png'}} />
style 和 source 是 Image 元件的屬性,即 props。style props 用於新增樣式,例如寬度、高度等,而 source props 用於為要顯示給使用者的影像分配 URL。source 和 style 是 Image 元件的內建 props。
您還可以使用儲存 URL 的變數,並將其用於 source props,如下所示:
let imgURI = { uri: 'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png' }; return ( <View style={styles.container}> <Image style={styles.stretch} source={imgURI} /> </View> );
以下示例顯示了使用內建 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 ( <View style={styles.container}> <Image style={styles.stretch} source={imgURI} /> </View> ); } const styles = StyleSheet.create({ container: { paddingTop: 50, paddingLeft: 50, }, stretch: { width: 200, height: 200, resizeMode: 'stretch', } }); export default MyImage;
示例 2:自定義元件中的 Props
您可以使用 props 將資訊從一個元件傳送到另一個元件。在下面的示例中,建立了兩個自定義元件:Student 和 Subject。
Subject 元件如下:
const Subject = (props) => { return ( <View> <Text style={{ padding:"10%", color:"green" }}>I am studying - {props.name}!</Text> </View> ); }
該元件接收引數 props。它用於在 Text 元件內顯示名稱為 props.name。讓我們看看如何從 Student 元件向 Subject 元件傳遞 props。
Student 元件如下:
const Student = () => { return ( <View> <Subject name="Maths" /> <Subject name="Physics" /> <Subject name="Chemistry" /> </View> ); }
在 Student 元件中,Subject 元件與 name props 一起使用。傳遞的值是數學、物理和化學。可以透過向 name props 傳遞不同的值來重複使用 Subject。
這是一個包含 Student 和 Subject 元件以及輸出的工作示例。
import React from 'react'; import { Text, View } from 'react-native'; const Subject = (props) => { return ( <View> <Text style={{ padding:"10%", color:"green" }}>I am studying - {props.name}! </Text> </View> ); } const Student = () => { return ( <View> <Subject name="Maths" /> <Subject name="Physics" /> <Subject name="Chemistry" /> </View> ); } export default Student;
輸出
廣告