React Native组件的属性简单地称为props。在React Native中,很多组件可以在创建时使用不同的参数进行自定义。这些参数称为props。是不可变的。
import React, { Component } from 'react'; import { Platform, StyleSheet, Image, Text, View } from 'react-native'; export default class App extends Component<{}> { render() { let imagePath = { uri: 'https://facebook.github.io/react-native/img/header_logo.png'}; return ( <View style={styles.container}> <Text style={styles.welcome}>Welcome to React Native!</Text> <Image source={imagePath} style={{width: 250, height: 250}} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#a7a6a9', }, welcome: { fontSize: 30, textAlign: 'center', margin: 20, } });
输出:
我们也可以在我们的组件中使用 props 。通过this.props 属性来获取值。
App.js
import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; class ChildClass extends Component { render() { return ( <View style={{alignItems: 'center'}}> <Text style={styles.welcome}>Hello {this.props.name}!</Text> </View> ); } } export default class ParentsClass extends Component { render() { return ( <View style={{alignItems: 'center'}}> <ChildClass name='Ashu' /> <ChildClass name='Aman' /> <ChildClass name='Max' /> </View> ); } } const styles = StyleSheet.create({ welcome: { fontSize: 30, } }); // 如果使用 Create React Native App,请跳过此行 AppRegistry.registerComponent('MyReactNativeApp', () => ParentsClass);
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)