React Native 系列(六)
阿新 • • 發佈:2017-08-25
過去 無效 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 系列(六)