标签:any code contain 生成 text 字符串 版本 问题 extends
本系列是基于React Native版本号0.44.3写的。在我们之前的通过props实现组件间传值的时候,大家有没有发现在父组件传递值过去,在子控件获取props的时候没有提示,那么如何能实现让其有提示呢?这篇文章将带领大家去认识一下PropTypes这个玩意。
问题: 在自定义组件的时候,通常需要暴露属性出去,并且设置属性类型,外界在使用自定义组件的属性的时候,需要有自动提示属性功能。
PropTypesPropTypes用处:
PropTypes定义属性,外界使用的时候会有提示注意点:
PropTypes必须要用static声明,否则无效果PropTypes只能用于React框架的自定义组件,默认JS是没有的,因为它是React框架中的。static:用来定义类方法或者类属性,定义类的方法和属性,生成的对象就自动有这样的属性了。
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.isRequireddefaultPropsstatic修饰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‘,
    },
});如果发现有错误的地方,欢迎各位指出,谢谢!
标签:any code contain 生成 text 字符串 版本 问题 extends
原文地址:http://www.cnblogs.com/yujihaia/p/7425857.html