该prop-types包允许您向组件添加运行时类型检查,以确保传递给组件的道具类型正确。例如,如果不将aname或isYummyprop传递给下面的组件,它将在开发模式下引发错误。在生产模式下,不进行道具类型检查。定义propTypes可以使您的组件更具可读性和可维护性。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { AppRegistry, Text, View } from 'react-native';
import styles from './styles.js';
class Recipe extends Component {
static propTypes = {
name: PropTypes.string.isRequired,
isYummy: PropTypes.bool.isRequired
}
render() {
return (
<View style={styles.container}>
<Text>{this.props.name}</Text>
{this.props.isYummy ? <Text>THIS RECIPE IS YUMMY</Text> : null}
</View>
)
}
}
AppRegistry.registerComponent('Recipe', () => Recipe);
// 使用组件
<Recipe name="Pancakes" isYummy={true} />多种道具类型
propTypes一个道具也可以有多个。例如,我正在使用的道具名称也可以是一个对象,我可以将其写为。
static propTypes = {
name: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object
])
}儿童道具
还有一个特殊的道具叫children,它不会像
<Recipe children={something}/>相反,您应该这样做
<Recipe> <Text>Hello React Native</Text> </Recipe>
然后可以在Recipe的渲染中执行此操作:
return (
<View style={styles.container}>
{this.props.children}
{this.props.isYummy ? <Text>THIS RECIPE IS YUMMY</Text> : null}
</View>
)你将有一个<Text>在你的组件Recipe说法Hello React Native,很酷的嗡嗡声?
儿童的propType是
children: PropTypes.node