大多数组件在创建时就可以使用各种参数来进行定制。用于定制的这些参数称为props(属性)。

一般来说,props属性用于组件之间数据传递。

自定义的组件也可以使用props。通过在不同的场景使用不同的属性定制,可以尽量提高自定义组件的复用范畴。只需在render函数中引用this.props,然后按需处理即可。

得到某一个具体的 Props值时,使用以下两种方式:

1-:

let name=this.props.name;

2-:

const {name}=this.props;

例子如下:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class Greeting extends Component {
    render() {
        return (
            <Text>Hello {this.props.name}!</Text>
        );
    }
}

export default class LearnDay extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={{alignItems: 'center'}}>
          <Greeting name='World' />
          <Greeting name='React' />
          <Greeting name='React Native' />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});

AppRegistry.registerComponent('LearnDay', () => LearnDay);

Greeting组件中将name作为一个属性来定制,这样可以复用这一组件来制作各种不同的“问候语”。

上面的例子把Greeting组件写在JSX语句中,用法和内置组件并无二致。以上的使用方式,可以称为组件化。

results matching ""

    No results matching ""