1. 程式人生 > >React Native 系列(六)

React Native 系列(六)

過去 無效 nat ive 字符 pes 自動 布爾 版本號

前言

本系列是基於React Native版本號0.44.3寫的。在我們之前的通過props實現組件間傳值的時候,大家有沒有發現在父組件傳遞值過去,在子控件獲取props的時候沒有提示,那麽如何能實現讓其有提示呢?這篇文章將帶領大家去認識一下PropTypes這個玩意。

PropTypes

  • 問題: 在自定義組件的時候,通常需要暴露屬性出去,並且設置屬性類型,外界在使用自定義組件的屬性的時候,需要有自動提示屬性功能。

  • 解決: 使用PropTypes
  • PropTypes用處:

    • 可以實現類型檢查,當傳入錯誤的屬性值,會報警告,但是不會報錯
    • PropTypes定義屬性,外界使用的時候會有提示
  • 註意點:

    • PropTypes必須要用static聲明,否則無效果
    • PropTypes只能用於React框架的自定義組件,默認JS是沒有的,因為它是React框架中的。
  • static:用來定義類方法或者類屬性,定義類的方法和屬性,生成的對象就自動有這樣的屬性了。

PropTypes的使用

  • PropTypes:屬性檢測,使用的時候需要先導入,在React框架中
import React, { Component, PropTypes } from ‘react‘;
  • 使用

在自定義組件添加如下代碼:

static propTypes = {
    name: PropTypes.string,
    age: PropTypes.number
}
  • 效果:
    技術分享

屬性類型

// 數組類型
PropTypes.array

// 布爾類型
PropTypes.bool

// 函數類型
PropTypes.func

// 數值類型
PropTypes.number

// 對象類型
PropTypes.object

// 字符串類型
PropTypes.string

// 規定prop為必傳字段
PropTypes.(類型).isRequired

// prop為任意類型
PropTypes.any.isRequired

給自定義屬性設置初始值

  • 如果想要給自定義屬性添加默認初始值,需要使用defaultProps
  • 註意:也是需要用static修飾
static defaultProps = {
    name: ‘scottDefault‘,
    age: 12
}

實戰演練

class ScottComponent extends Component {
    static propTypes = {
        name: PropTypes.string.isRequired,
        age: PropTypes.number
    }

    static defaultProps = {
        name: ‘scottDefault‘,
        age: 12
    }

    render(){
        return (
            <View style={styles.scottStyle}>
                <Text>組件名字:{this.props.name}</Text>
                <Text>組件年齡:{this.props.age}</Text>
            </View>
        );
    }
}

// 主組件
export default class RNDemoOne extends Component {
  render() {
    return (
        <View style={styles.container}>
            <ScottComponent/>
        </View>
    );
  }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },

    scottStyle: {
        flex: 1,
        backgroundColor: ‘#F5FCFF‘,
        justifyContent: ‘center‘,
        alignItems: ‘center‘,
    },
});

致謝

如果發現有錯誤的地方,歡迎各位指出,謝謝!

React Native 系列(六)