2.1.2 组件中的 prop

在 RN 中,prop 是从外部传递给组件的数据。一个 RN 组件通过定义自己能够接受的 prop 就定义了自己的对外公共接口。 每个 RN 组件都是独立存在的模块,组件之外的一切都是外部世界,外部世界就是通过 prop 来和组件对话的。

给 prop 赋值

我们从组件外部世界来看,prop 是如何使用的。

//App.js

export default class App extends Component<Props> {

    render() {
        return ( // 渲染布局
            <View style={styles.container}>
                <Counter style={{margin:10}} initValue={1}/>
                <Counter style={{margin:10}} initValue={2}/>
                <Counter style={{margin:10}} initValue={3}/>
            </View>
        );
    }
}

代码片段2-1-4

组件是可以复用的, 参考代码片段2-1-4,我们复用了 Counter 组件,每个组件分别使用了 style 和 initValue 属性,当属性不是字符串类型时,在 JSX 中必须用花括号 {} 把属性值包住,所以 style 属性的值有两层花括号,外层花括号代表是 JSX 的语法,内层的花括号代表这是一个对象常量。

我们通过 style 属性传递给 Counter 组件样式,initValue 想用来作为显示数字的初始值,而这两个属性目前并没有被 Counter 使用。接下来看一下如何使用该属性。

读取 prop 值

首先是构造函数,代码如下:

// /src/component/Counter.js

export default class Counter extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            value: this.props.initValue || 1
        };
    }
}

每个组件一定要记得在构造函数的第一行声明 super(props) ,否则所有成员函数就无法通过 this.props 访问到父组件传递过来的 props 值。我们把 initValue 的值在状态机变量初始化的时候赋值给了 value,如果读取不到属性 value 值就为1。

通过this.props.style 就可以使用外部传递的 style 属性。我们一般把外部传来的样式声明在组件内最外层的 <View> 上,参考下面代码,通过数组形式和之前的样式合并在了一起。

// /src/component/Counter.js

render() {
   return ( // 渲染布局
        <View style={[this.props.style, styles.operatingBox]}>
            省略 ...
        </View>
   );
}

运行效果,如图 2-4 所示。

图2-4 运行结果 图2-4 运行结果

查看代码

如果你已经从 GitHub 上克隆了这个程序的 Git 仓库,那么可以执行 git checkout 2b签出程序的这个版本。

results matching ""

    No results matching ""