React Native 中的 props 是什么?

WBOY
WBOY 转载
2023-08-29 18:13:10 473浏览

Props 是有助于修改 React 组件的属性。创建的组件可以使用 props 概念与不同的参数一起使用。使用 props,您可以将信息从一个组件传递到另一个组件,同时根据您的要求重用该组件。

如果您精通 ReactJS,您就会熟悉 props,同样的React Native 中遵循概念。

让我们看一个示例来解释 props 是什么。

示例 1:React Native 内置组件中的 Props

考虑图像组件 -

<Image
   style={styles.stretch} source={{uri: 'https://pbs.twimg.com/profile_images/486929358120964097   /gNLINY67_400x400.png'}}
/>

样式是属性,即图像组件的道具。 style props 用于添加样式,即宽度、高度等,而 source props 用于将 url 分配给要显示给用户的图像。 Image 组件的源和样式以及内置属性。

您还可以使用存储 url 的变量并将其用于源属性,如下所示 -

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>
);

下面的示例展示了使用内置道具显示简单图像 -

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 将信息从一个组件发送到另一个组件。在下面的示例中,创建了两个自定义组件:学生和主题。

主题组件如下 -

const Subject = (props) => {
   return (
      <View>
      <Text style={{ padding:"10%", color:"green" }}>I am studying - {props.name}!</Text>
      </View>
   );
}

该组件采用参数 props。它在 Text 组件内部使用,将名称显示为 props.name。让我们看看如何将属性从学生组件传递到主题组件。

学生组件如下 -

const Student = () => {
   return (
      <View>
         <Subject name="Maths" />
         <Subject name="Physics" />
         <Subject name="Chemistry" />
      </View>
   );
}

在 Student 组件中,Subject 组件与 name 属性一起使用。传递的值是数学、物理和化学。通过将不同的值传递给 name 属性,可以重复使用主题。

这是一个包含 Student 和主题组件以及输出的工作示例。

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;

输出

React Native 中的 props 是什么?

以上就是React Native 中的 props 是什么?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除