# React Native 组件属性 props

前面章节 React Native 组件状态 state (opens new window) 中我们简单的介绍了下 组件属性 props

本章节我们将详细介绍 组件属性 props 以及如何将属性状态 state 和属性组件 props 组合在一起使用。

组件的调用者可以通过 属性 将数据传递给组件,然后组件内部可以通过 组件属性 props 来获取调用者传递的数据。

调用者通过属性传递数据

<SiteNameComponent onPress={this.updateState} name={name} />
1

组件内部通过组件属性 props 来获取传递给组件的数据

const SiteNameComponent = (props) => {
   return (
      <View>
         <Text onPress = {props.onPress}>
            {props.name}
         </Text>
      </View>
   )
}
1
2
3
4
5
6
7
8
9

因为数据可以通过属性来传递,组件可以没有状态,不用状态来保存任何中间数据。对于没有状态的组件,我们称之为 表现组件

因此我们可以将组件分为两大类:

  1. 容器组件

    容器组件是普通的组件,使用 ES6 类 来实现,既包括组件属性,也包含 组件状态

    最重要的是 容器组件有自己的状态和行为处理函数

  2. 纯表现组件

    纯表现组件只用于展现数据,数据来源可以是写死的固定不变的,也可以是通过属性传递给组件的。

    纯表现组件没有自己的内部状态,所有数据都因为外部而变。

# 容器组件

容器组件是最普通的组件,使用 ES6 类 来实现,既包括组件属性,也包含组件状态。

# 使用原则

  1. 如果一个组件需要更新自己的状态,那么该组件就是容器组件。
  2. 容器组件有着自己的状态 state,也可以通过属性 props 接收外部的数据来更新自己的状态。
  3. 如果不需要保存状态,建议不要使用容器组件。

# 范例

容器组件是最普通的组件, React Native 内置的大部分组件都是容器组件,它们多有一个 state 来保存状态。

下面的代码,我们使用容器组件来实现站点名称的展示,我们通过属性将外部数据作为初始值传递给组件,然后组件自己内部处理用户的点击。

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

class SiteNameComponent extends React.Component {

    constructor(props) {
        super(props)
        this.state = { name: props.name }
    }

    updateState = () => {
        const name = this.state.name == '简单教程' ? '简单教程,简单编程' : '简单教程'
        this.setState({name:name})
    }

    render() {
        const { name } = this.state
        return (
        <View>
            <Text onPress={this.updateState}>{name}</Text>
        </View>
        )
    }
}

export default class App extends React.Component {

    render() {
        return (
            <View style={styles.container}>
                <SiteNameComponent name={'简单教程'} />
            </View>
        )
    }
}

const styles = StyleSheet.create ({
   container: {
      margin:10
   },
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

演示

Last Updated: 8/9/2022, 4:24:39 PM