Props verification for React and Vue

Table of contents

Props verification in React

Single type validator in react

Set attribute type and default value

 Set required properties

Combined type validator in react

PropTypes.oneOfType

 PropTypes.arrayOf

PropTypes.objectOf

​Edit PropTypes.shape

PropTypes.node

Props validation in Vue

Vue data validation: through variable name: specific type method

Vue data validation: validation with default value

Set required attributes through required

one of many types

 Object array validation and array elements are objects with specific properties

Custom validation function


Why use props verification?

There are two benefits of using props verification:

1. You can clearly know the types of attributes in the component and which attributes are required.

2. When there is an error in the transmitted data, an error will be reported, making it easy to locate the problem.

This article will provide data verification methods and examples in React and vue.

Props verification in React

propTypes is used in react to verify props. Default values ​​can be set through defaultProps, and attribute types can be specified through propTypes.

Basic usage example:

import React from "react";
// 引入PropTypes
import PropTypes from 'prop-types'
export default class Child extends React.Component {

    constructor(props) {
        super(props)
    }
    render() {
        return (
            <div></div>
        )
    }
}
// 规定属性的类型-将propTypes设置成一个类构造函数属性
Child.propTypes={

}
// 设置默认值
Child.defaultProps = {

}

Single type validator in react

PropTypes can be used to verify string (string), number (number or value that can be parsed into a number), bool (Boolean), object (object), array (array), and func (function) types.

Set attribute type and default value

Usage example:

// 规定属性的类型-将propTypes设置成一个类构造函数属性
Child.propTypes = {
    arrValue: PropTypes.array,//数组类型
    boolValue: PropTypes.bool,//布尔类型
    funcValue: PropTypes.func,//函数类型
    numValue: PropTypes.number,//数字类型
    objValue: PropTypes.object,//对象类型
    strValue: PropTypes.string,//字符串类型
}
// 设置默认值
Child.defaultProps = {
    arrValue: [1, 2],
    boolValue: false,
    numValue: 0,
    objValue: {
        name: 'lisi'
    },
    strValue: '123'
}

When no parameters are passed (the set default value will be used):

 father:

import React from "react";
import Child from './Child'
export default class PropsDemo extends React.Component {

    constructor(props) {
        super(props)
        this.print = this.print.bind(this)
    }

    print() {
        console.log('打印日志')
    }

    render() {
        return (
            <div>
                <Child></Child>
            </div >
        )
    }
}

 Subclass:

import React from "react";
// 引入PropTypes
import PropTypes from 'prop-types'
export default class Child extends React.Component {
    printData() {
        this.props.funcValue()
    }
    render() {
        const { arrValue, boolValue, numValue, objValue, strValue } = this.props
        return (
            <div>
                <div>{arrValue.join(',')}</div>
                <div style={
   
   { color: boolValue ? '#00ffff' : '#ff7f50' }}>布尔类型</div>
                <div>学生信息:{`${objValue.name}-${objValue.age}`}</div>
                <div>得分:{numValue}</div>
                <div>备注:{strValue}</div>
                <button onClick={this.printData.bind(this)}>打印</button>
            </div>
        )
    }
}
// 规定属性的类型-将propTypes设置成一个类构造函数属性
Child.propTypes = {
    arrValue: PropTypes.array,//数组类型
    boolValue: PropTypes.bool,//布尔类型
    funcValue: PropTypes.func,//函数类型
    numValue: PropTypes.number,//数字类型
    objValue: PropTypes.object,//对象类型
    strValue: PropTypes.string,//字符串类型
}
// 设置默认值
Child.defaultProps = {
    arrValue: [1, 2],
    boolValue: false,
    numValue: 60,
    objValue: {
        name: 'lisi',
        age: 20
    },
    strValue: 'xxx'
}

 Pass parameters (use passed values)

import React from "react";
import Child from './Child'
export default class PropsDemo extends React.Component {

    constructor(props) {
        super(props)
        this.print = this.print.bind(this)
    }

    print() {
        console.log('打印日志')
    }

    render() {
        const arrValue = [3, 4, 5]
        const boolValue = true
        const numValue = 88
        const objValue = {
            name: '王五',
            age: 22
        }
        const strValue = '优秀'
        return (
            <div>
                <Child
                    arrValue={arrValue}
                    boolValue={boolValue}
                    numValue={numValue}
                    objValue={objValue}
                    funcValue={this.print}
                    strValue={strValue}
                ></Child>
            </div >
        )
    }
}

 Set required properties

You can set the attribute to be required through isRequired. If the parent component is not passed and there is no default value, an error message will be reported.

Annotate the passing of strValue

                <Child
                    arrValue={arrValue}
                    boolValue={boolValue}
                    numValue={numValue}
                    objValue={objValue}
                    funcValue={this.print}
                    // strValue={strValue}
                ></Child>

Set strValue as a required attribute and comment out the setting of the default value

Child.propTypes = {
    arrValue: PropTypes.array,//数组类型
    boolValue: PropTypes.bool,//布尔类型
    funcValue: PropTypes.func,//函数类型
    numValue: PropTypes.number,//数字类型
    objValue: PropTypes.object,//对象类型
    strValue: PropTypes.string.isRequired,//字符串类型
}
// 设置默认值
Child.defaultProps = {
    arrValue: [1, 2],
    boolValue: false,
    numValue: 60,
    objValue: {
        name: 'lisi',
        age: 20
    },
    // strValue: 'xxx'
}

 Run the code:

Let go of the default value setting just commented out and find that the error is no longer reported.

Child.propTypes = {
    arrValue: PropTypes.array,//数组类型
    boolValue: PropTypes.bool,//布尔类型
    funcValue: PropTypes.func,//函数类型
    numValue: PropTypes.number,//数字类型
    objValue: PropTypes.object,//对象类型
    strValue: PropTypes.string.isRequired,//字符串类型
}
// 设置默认值
Child.defaultProps = {
    arrValue: [1, 2],
    boolValue: false,
    numValue: 60,
    objValue: {
        name: 'lisi',
        age: 20
    },
    strValue: 'xxx'
}

 

Let go of the passed strValue setting just commented out and find that no error will be reported.

                <Child
                    arrValue={arrValue}
                    boolValue={boolValue}
                    numValue={numValue}
                    objValue={objValue}
                    funcValue={this.print}
                    strValue={strValue}
                ></Child>

 

Combined type validator in react

There are several types of combined type validators:

oneOfType: The attribute must be one of the specified set of types

arrayOf: The attribute must be an array consisting of the specified elements

objectOf: The attribute must be an object with an attribute value of the specified type. That is to say, the object must have an attribute of the specified type.

The shape: attribute must be an object that conforms to a specific format, and it needs to have the same set of attributes.

node: attribute must be a renderable value: number, string, element or array

element: attribute must be a React element

instanceOf: The attribute must be an instance of the specified class

oneOf: ensures that the property is restricted to one of a set of enumeration values

PropTypes.oneOfType

father:

       const dataValue1 = '测试'//字符串
        const dataValue2 = 234//数字
        const dataValue3 = { name: '王五' }//非字符串和数字
        return (
            <div>
                <Child
                    dataValue1={dataValue1}
                    dataValue2={dataValue2}
                    dataValue3={dataValue3}
                ></Child>
            </div >
        )

Subclass:

import React from "react";
// 引入PropTypes
import PropTypes from 'prop-types'
export default class Child extends React.Component {

    componentDidMount() {
        console.log('dataValue3:', this.props.dataValue3)
    }

    render() {
        return (
            <div>
                <div>dataValue1:{this.props.dataValue1}</div>
                <div>dataValue1:{this.props.dataValue2}</div>
            </div>
        )
    }
}
// 规定属性的类型-将propTypes设置成一个类构造函数属性
Child.propTypes = {
    dataValue1: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number
    ]),
    dataValue2: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number
    ]),
    dataValue3: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number
    ])
}

You can see that dataValue1 and dataValue2 are both one of the specified types and can be used normally; while dataValue3 does not pass the specified type, there will be a reminder.

 PropTypes.arrayOf

father:

 render() {
        const dataValue1 = [1, 2, 3, 4]//元素是number类型
        const dataValue2 = ['1', '2', '3', '4']//元素是string类型

        return (
            <div>
                <Child
                    dataValue1={dataValue1}
                    dataValue2={dataValue2}
                ></Child>
            </div >
        )
    }

Subclass:

import React from "react";
// 引入PropTypes
import PropTypes from 'prop-types'
export default class Child extends React.Component {

    render() {
        return (
            <div>
                <div>dataValue1:{this.props.dataValue1.join(',')}</div>
                <div>dataValue1:{this.props.dataValue2.join(',')}</div>
            </div>
        )
    }
}
// 规定属性的类型-将propTypes设置成一个类构造函数属性
Child.propTypes = {
    dataValue1: PropTypes.arrayOf(PropTypes.number),
    dataValue2: PropTypes.arrayOf(PropTypes.number),
}

 You can see that there is no error prompt when the array element is a number, but there is an error prompt when the array element is not a number.

PropTypes.objectOf

father:

    render() {
        const dataValue1 = {
            value1: 1,
            value2: 2,
            value3: 3
        }
        const dataValue2 = {
            value1: "1",
            value2: "2",
            value3: "3"
        }

        return (
            <div>
                <Child
                    dataValue1={dataValue1}
                    dataValue2={dataValue2}
                ></Child>
            </div >
        )
    }

Subclass:

import React from "react";
// 引入PropTypes
import PropTypes from 'prop-types'
export default class Child extends React.Component {

    getValueStr(obj) {
        let str = ''
        for (const key in obj) {
            str = `${str}${obj[key]},`
        }
        return str
    }

    render() {
        const { dataValue1, dataValue2 } = this.props
        const dataValue1Str = this.getValueStr(dataValue1)
        const dataValue2Str = this.getValueStr(dataValue2)
        return (
            <div>
                <div>dataValue1:{dataValue1Str}</div>
                <div>dataValue1:{dataValue2Str}</div>
            </div>
        )
    }
}
// 规定属性的类型-将propTypes设置成一个类构造函数属性
Child.propTypes = {
    dataValue1: PropTypes.objectOf(PropTypes.number),
    dataValue2: PropTypes.objectOf(PropTypes.number),
}

PropTypes.shape

 father:

    render() {
        const dataValue1 = {
            name: '张三',
            age: 20
        }
        const dataValue2 = {
            name: '张三',
            age: "20"//age不传递number类型
        }
        const dataValue3 = {
            name: '张三',//少传递一个属性
        }
        const dataValue4 = {
            name: '张三',
            age: 20,
            num: 88,//多传递一个属性
        }

        return (
            <div>
                <Child
                    dataValue1={dataValue1}
                    dataValue2={dataValue2}
                    dataValue3={dataValue3}
                    dataValue4={dataValue4}
                ></Child>
            </div >
        )
    }

Subclass:

import React from "react";
// 引入PropTypes
import PropTypes from 'prop-types'
export default class Child extends React.Component {

    getValueStr(obj) {
        let str = ''
        for (const key in obj) {
            str = `${str}${obj[key]},`
        }
        return str
    }

    render() {
        const { dataValue1, dataValue2, dataValue3, dataValue4 } = this.props
        const dataValue1Str = this.getValueStr(dataValue1)
        const dataValue2Str = this.getValueStr(dataValue2)
        const dataValue3Str = this.getValueStr(dataValue3)
        const dataValue4Str = this.getValueStr(dataValue4)
        return (
            <div>
                <div>dataValue1:{dataValue1Str}</div>
                <div>dataValue2:{dataValue2Str}</div>
                <div>dataValue3:{dataValue3Str}</div>
                <div>dataValue4:{dataValue4Str}</div>
            </div>
        )
    }
}
// 规定属性的类型-将propTypes设置成一个类构造函数属性
Child.propTypes = {
    dataValue1: PropTypes.shape({
        name: PropTypes.string,
        age: PropTypes.number
    }),
    dataValue2: PropTypes.shape({
        name: PropTypes.string,
        age: PropTypes.number
    }),
    dataValue13: PropTypes.shape({
        name: PropTypes.string,
        age: PropTypes.number
    }),
    dataValue14: PropTypes.shape({
        name: PropTypes.string,
        age: PropTypes.number
    }),
}

 

It can be seen that there will be no error reminder for missing attributes or adding attributes, but if the attribute type passed is inconsistent with the predetermined one, there will be an error reminder.

PropTypes.node

Parent component:

    render() {
        const dataValue1 = 123//数字
        const dataValue2 = '张三'//字符串
        const dataValue3 = [1, 2, 3]
        const dataValue4 = {//对象
            name: '张三',
            age: 20,
            num: 88,
        }

        return (
            <div>
                <Child
                    dataValue1={dataValue1}
                    dataValue2={dataValue2}
                    dataValue3={dataValue3}
                    dataValue4={dataValue4}
                ></Child>
            </div >
        )
    }

 Subassembly:

import React from "react";
// 引入PropTypes
import PropTypes from 'prop-types'
export default class Child extends React.Component {

    getValueStr(obj) {
        let str = ''
        for (const key in obj) {
            str = `${str}${obj[key]},`
        }
        return str
    }

    render() {
        const { dataValue1, dataValue2, dataValue3, dataValue4, } = this.props
        const dataValue4Str = this.getValueStr(dataValue4)
        return (
            <div>
                <div>dataValue1:{dataValue1}</div>
                <div>dataValue2:{dataValue2}</div>
                <div>dataValue3:{dataValue3.join(',')}</div>
                <div>dataValue4:{dataValue4Str}</div>
            </div>
        )
    }
}
// 规定属性的类型-将propTypes设置成一个类构造函数属性
Child.propTypes = {
    dataValue1: PropTypes.node,
    dataValue2: PropTypes.node,
    dataValue3: PropTypes.node,
    dataValue4: PropTypes.node,
}

It can be seen that when the predetermined attribute is of PropTypes.node type, numbers, strings, and arrays can be passed, but an error message will be reported when passing the object type. Note that the PropTypes.node type is not limited to numbers, strings, and arrays, but can also be any other renderable element.

Props validation in Vue

The following types can be checked in vue: String, Number, Boolean, Array, Object, Date, Function, Symbol and custom types.

Vue data validation: through variable name: specific type method

Parent component:

<template>
  <div>
    <PropsChildDemo
      :name="name"
      :age="age"
      :obj="obj"
      :obj2="obj2"
    ></PropsChildDemo>
  </div>
</template>
<script>
import PropsChildDemo from "./PropsChildDemo.vue";
export default {
  name: "PropsDemo",
  components: { PropsChildDemo },
  data() {
    return {
      name: "张三",
      age: 20,
      obj: {
        name: "李四",
        age: 21,
      },
      obj2: {
        func: function () {
          console.log("打印");
        },
      },
    };
  },
};
</script>

Subassembly:

<template>
  <div>
    <div>姓名:{
   
   { name }}</div>
    <div>年龄:{
   
   { age }}</div>
    <div>姓名:{
   
   { obj.name }};年龄:{
   
   { obj.age }}</div>
    <button @click="obj2.func">打印</button>
  </div>
</template>
<script>
export default {
  name: "PropsChildDemo",
  components: {},
  props: {
    name: String,//直接说明name为String类型
    age: Number,
    obj: Object,
    obj2: {
      func: Function,
    },
  },
  data() {
    return {};
  },
  methods: {},
};
</script>

 

Vue data validation: validation with default value

To set the default value in Vue, use the default attribute. At this time, you need to use the type attribute when setting the data type.

<template>
  <div>
    <PropsChildDemo :obj2="obj2"></PropsChildDemo>
  </div>
</template>
<script>
import PropsChildDemo from "./PropsChildDemo.vue";
export default {
  name: "PropsDemo",
  components: { PropsChildDemo },
  data() {
    return {
      name: "张三",
      age: 20,
      obj: {
        name: "李四",
        age: 21,
      },
      obj2: {
        func: function () {
          console.log("打印");
        },
      },
    };
  },
};
</script>
<template>
  <div>
    <div>姓名:{
   
   { name }}</div>
    <div>年龄:{
   
   { age }}</div>
    <div>姓名:{
   
   { obj.name }};年龄:{
   
   { obj.age }}</div>
    <button @click="obj2.func">打印</button>
  </div>
</template>
<script>
export default {
  name: "PropsChildDemo",
  components: {},
  props: {
    name: {
      // 设置类型
      type: String,
      // 设置默认值
      default: "XXX",
    },
    age: {
      type: Number,
      default: 0,
    },
    obj: {
      type: Object,
      //  注意:对象和数组的默认值必须从一个工厂函数获取
      default: function () {
        return {
          name: "xxxx",
          age: -1,
        };
      },
    },
    obj2: {
      func: Function,
    },
  },
  data() {
    return {};
  },
  methods: {},
};
</script>

Note: Default values ​​for objects and arrays must be obtained from a factory function.

Set required attributes through required

    name: {
      // 设置类型
      type: String,
      // 设置默认值
      default: "XXX",
      // 通过required设置必须属性
      required: true,
    },

 After setting name as a required attribute through required, if the name field is not passed, an error message will appear.

 

one of many types

<template>
  <div>数据验证</div>
</template>
<script>
export default {
  name: "PropsChildDemo",
  components: {},
  props: {
    info: [String, Number, Boolean],
  },
  data() {
    return {};
  },
};
</script>

info must be one of String, Number, and Boolean, otherwise there will be a prompt.

 An object is passed:

<template>
  <div>
    <PropsChildDemo :info="info"></PropsChildDemo>
  </div>
</template>
<script>
import PropsChildDemo from "./PropsChildDemo.vue";
export default {
  name: "PropsDemo",
  components: { PropsChildDemo },
  data() {
    return {
      info: {
        nam: "张三",
        age: 20,
      },
    };
  },
};
</script>

Pass a string:

<template>
  <div>
    <PropsChildDemo :info="info"></PropsChildDemo>
  </div>
</template>
<script>
import PropsChildDemo from "./PropsChildDemo.vue";
export default {
  name: "PropsDemo",
  components: { PropsChildDemo },
  data() {
    return {
      info: "张三",
    };
  },
};
</script>

 

 Object array validation and array elements are objects with specific properties

Verify that info is an array, and the array elements are objects composed of name and age attributes.

<template>
  <div>数据验证</div>
</template>
<script>
export default {
  name: "PropsChildDemo",
  components: {},
  props: {
    info: {
      // 设置必须
      required: true,
      type: Array,
      // 验证info是一个数组,并且数组元素是由name,age属性组成的对象
      validator(value) {
        return value.every((item) => {
          const { name, age } = item;
          return Boolean(name && age);
        });
      },
    },
  },
  data() {
    return {};
  },
};
</script>

Pass one less attribute:

<template>
  <div>
    <PropsChildDemo :info="info"></PropsChildDemo>
  </div>
</template>
<script>
import PropsChildDemo from "./PropsChildDemo.vue";
export default {
  name: "PropsDemo",
  components: { PropsChildDemo },
  data() {
    return {
      info: [
        {
          name: "zhangsan",
          age: 20,
        },
        //   其中一个元素少一个属性
        {
          name: "wangwu",
        },
      ],
    };
  },
};
</script>

 

Pass on request: 

<template>
  <div>
    <PropsChildDemo :info="info"></PropsChildDemo>
  </div>
</template>
<script>
import PropsChildDemo from "./PropsChildDemo.vue";
export default {
  name: "PropsDemo",
  components: { PropsChildDemo },
  data() {
    return {
      info: [
        {
          name: "zhangsan",
          age: 20,
        },
        {
          name: "wangwu",
          age: 21,
        },
      ],
    };
  },
};
</script>

 

Pass one more parameter:

<template>
  <div>
    <PropsChildDemo :info="info"></PropsChildDemo>
  </div>
</template>
<script>
import PropsChildDemo from "./PropsChildDemo.vue";
export default {
  name: "PropsDemo",
  components: { PropsChildDemo },
  data() {
    return {
      info: [
        // 多传递一个参数
        {
          name: "zhangsan",
          age: 20,
          num: 88,
        },
      ],
    };
  },
};
</script>

 

Therefore, if you pass less or incorrectly, the verification will fail. If you pass more or as required, the verification will pass. 

 

Custom validation function

<template>
  <div>
    <PropsChildDemo :info="info"></PropsChildDemo>
  </div>
</template>
<script>
import PropsChildDemo from "./PropsChildDemo.vue";
export default {
  name: "PropsDemo",
  components: { PropsChildDemo },
  data() {
    return {
      info: "zhaoliu",
    };
  },
};
</script>
<template>
  <div>{
   
   { info }}</div>
</template>
<script>
export default {
  name: "PropsChildDemo",
  components: {},
  props: {
    info: {
      validator(value) {
        return ["zhangsan", "lisi", "wangwu"].indexOf(value) !== -1;
      },
    },
  },
  data() {
    return {};
  },
};
</script>

info must be one of zhangsan, lisi, and wangwu, otherwise an error message will appear.

Pass one of zhangsan, lisi, and wangwu, and there will be no error message:

<template>
  <div>
    <PropsChildDemo :info="info"></PropsChildDemo>
  </div>
</template>
<script>
import PropsChildDemo from "./PropsChildDemo.vue";
export default {
  name: "PropsDemo",
  components: { PropsChildDemo },
  data() {
    return {
        info: "wangwu",
    };
  },
};
</script>

 

 

Guess you like

Origin blog.csdn.net/Celester_best/article/details/126025055