React Native Props(属性)使用详解

BG:

目前的Component仍然在react框架中,也就是说React Native使用的Component是react框架中的组件,而Component有两大数据管理核心State和Props。也就是说即使你仅仅想用React Native开发APP,你也需要去了解React的相关知识,比如Component、State和Props,本文主要介绍Props的使用。
State使用详解戳这里

组件(Components) 让你可以将用户界面分成独立的,可复用的小部件,并可以对每个部件进行单独的设计。你可以在这里找到详细的组件API参考

从定义上来说, 组件就像JavaScript的函数。组件可以接收任意输入(称为”props”), 并返回 React 元素,用以描述屏幕显示内容。

一、Props 是什么?

Props即属性(Property), 在代码中写作 props ,props可用作父子组件之间传值(同时对传递的数据的类型进行约束),但是子组件不能修改props,对自身来说props是只读的。

注意:
React 组件的构造函数在 挂载(mounted) 之前被调用。 在实现 React.Component 子类的构造函数时, 应该在任何其他声明之前调用super(props)。 否则,this.props 将在 constructor(构造函数) 中是 undefined(未定义) ,这将导致 bug 。

通常,React 构造函数只用于两个目的:

Note
避免复制 属性(props) 到 状态(state) ! 这是一个常见的错误:

constructor(props) {
super(props);
// Don't do this!
this.state = { color: props.color };
}

问题是,这是不必要的(直接使用 this.props.color 代替),并会>产生错误(对 color属性(props)的更新不会反映在状态中)。

仅在你故意要忽略 属性(props)更新时,使用此模式。 在这种情>况下,将 属性(props) 重命名为 initialColordefaultColor 是有>意义的。 然后,你可以强制组件通过 改变它的key 来重置它的内部状态。

如果你认为你需要一些状态(state)来依赖于这个属性(props),阅读我们的 避免派生 状态(state) 的博客文章,以了解你需要做什么。

二、Props传值

1.默认Props

通过组件类的 defaultProps 属性为 props 设置默认值,实例如下:

export default class PropComponent extends Component {
    static defaultProps={
         name: '张三',
         sex:'man',
         tel:'13866666666'
        }
}

声明defaultProps 属性后,在遇到没有被赋值的属性时,就会读取默认属性值。

2. Props赋值的几种方式

我们有下面这样一个子组件PropComponent:

export default class PropComponent extends Component {
    static defaultProps={
         name: '张三',
         sex:'man',
         tel:'13866666666'
        }
    constructor(props) {
        super(props);
    };

    render(){
        return (
            <View style={styles.container}>
                <Text>姓名:{this.props.name} 年龄:{this.props.age}  性别:{this.props.sex} 电话:{this.props.tel}</Text>
            </View>
        );
    }
}

简单赋值

<PropComponent name='张三' age=20/>

延展操作符赋值
延展操作符:...,延展操作符很方便,还可用于函数的可变参数传递。

var params = {name: '李四', age:'30', sex: 'man'};

...

<PropComponent {...params}/>
...

解构赋值
对象的解构赋值用于从一个对象取值,相当于将所有可遍历的、但尚未被读取的属性,分配到指定的对象上面.

var params2 = {name: '张解构', age: 20, sex: 'man'};
let {name, age} = params2;
...
<PropComponent name={name} age={age}/>
...

三、Props类型检查

React.PropTypes 在 React v15.5 版本后已经移到了 prop-types 库。
<script src="https://cdn.bootcss.com/prop-types/15.6.1/prop-types.js"></script>

Props 验证使用 静态propTypes,它可以保证我们的应用组件被正确使用,React.PropTypes 提供很多验证器 (validator) 来验证传入数据是否有效。当向 props 传入无效数据时,JavaScript 控制台会抛出警告。
比如校验age属性类型必须是number,当你传入的是string类型时:


4130078-3a2e1615c3e8c4eb.png
image.png

示例如下:

static propTypes={
        name: PropTypes.string.isRequired,
        age: PropTypes.number,
        //要求属性取值为特定的几个值
        sex: PropTypes.oneOf(['man', 'woman']),

        //要求属性可以为指定类型中的任意一个
        tel: PropTypes.oneOfType([
            PropTypes.string,
            PropTypes.number,
          ]),
    }

全部类型检查说明:

//JS 基本数据类型
export const any: Requireable<any>;
export const array: Requireable<any[]>;
export const bool: Requireable<boolean>;
export const func: Requireable<(...args: any[]) => any>;
export const number: Requireable<number>;
export const object: Requireable<object>;
export const string: Requireable<string>;

//可以被渲染的对象 numbers, strings, elements 或 array
export const node: Requireable<ReactNodeLike>;

////  React 元素
export const element: Requireable<ReactElementLike>;

export const symbol: Requireable<symbol>;

// 用 JS 的 instanceof 操作符声明 prop 为类的实例。
export function instanceOf<T>(expectedClass: new (...args: any[]) => T): Requireable<T>;

// 用 enum 来限制 prop 只接受指定的值。
export function oneOf<T>(types: T[]): Requireable<T>;

// 可以是多个对象类型中的一个
export function oneOfType<T extends Validator<any>>(types: T[]): Requireable<NonNullable<InferType<T>>>;

 // 指定类型组成的数组
export function arrayOf<T>(type: Validator<T>): Requireable<T[]>;

// 指定类型的属性构成的对象
export function objectOf<T>(type: Validator<T>): Requireable<{ [K in keyof any]: T; }>;

//指定属性及其类型的对象
export function shape<P extends ValidationMap<any>>(type: P): Requireable<InferProps<P>>;

export function exact<P extends ValidationMap<any>>(type: P): Requireable<Required<InferProps<P>>>;

任意类型加上 isRequired 来使 prop 不可空,比如name不能为空:

static propTypes={
        name: PropTypes.string.isRequired,
        age: PropTypes.number,
    }

部分类型举例:

PropTypes.shape

//子组件CheckObjectComponent 中类型约束:
static propTypes={
        //指定属性及其类型的对象,
        position: PropTypes.shape({
            num: PropTypes.number.isRequired,
            job:PropTypes.string,
        }),
    }

//父组件调用:

var shapeParams = {name: '王五', age: 23, sex: 'man',position:{num:'1010001',job:"iOS开发"}};
...
<CheckObjectComponent position = {shapeParams. position} />
//或延展写法:
<CheckObjectComponent {...shapeParams}/>
...

PropTypes.element
约束属性是React元素,实例:

//子组件CheckElementComponent中:
export class CheckElementComponent extends Component {
    static propTypes={
        //元素
        addressElement:PropTypes.element,
    }
    
    constructor(props) {
        super(props);
    };

    render(){
        return (
            <View style={styles.container}>
                <View><Text>地址:</Text>{this.props.addressElement}</View>
            </View>
        );
    }
}

//父组件调用:
var elementParams = {addressElement:<View><Image source={require('../../images/tabBar/me_normal.png')}></Image><Text style={[{color:'blue'}]}>我在北京....</Text></View>};
...
<CheckElementComponent {...elementParams}/>

PropTypes.instanceOf

//子组件CheckInstanceOfComponent:
export class CheckInstanceOfComponent extends Component {
    static propTypes={
        //声明属性为某个类的实例
    addressElement:PropTypes.instanceOf(CheckElementComponent),
    }
    
    constructor(props) {
        super(props);
    };

    render(){
        return (
            <View style={styles.container}>
                {this.props.addressElement}
            </View>
        );
    }
}

//父组件调用:

var temElement = {addressElement:<Text style={[{color:'blue'}]}>我是instanceOf(CheckElementComponent)实例!</Text>};
var testInstance = <CheckElementComponent {...temElement}></CheckElementComponent>
...
<CheckInstanceOfComponent {...instanceOfParams}/>
...

说到props就离不开生命周期函数componentWillReceiveProps,componentWillReceiveProps函数使用注意你可以戳这里

以上是Props的使用介绍,希望能帮到你,欢迎留言交流~~~

猜你喜欢

转载自blog.csdn.net/weixin_33850015/article/details/86947581