React和Vue的props驗(yàn)證示例詳解
為什么要使用props校驗(yàn)?
使用props校驗(yàn)有兩個(gè)好處:
1、可以很清晰的知道組件中屬性的類型以及哪些屬性是必需的
2、傳遞的數(shù)據(jù)出現(xiàn)錯(cuò)誤時(shí)會(huì)報(bào)錯(cuò),可以很容易定位問題
本文將會(huì)提供React和vue中的數(shù)據(jù)校驗(yàn)方法和示例。
React中的props校驗(yàn)
react中使用propTypes來對(duì)props進(jìn)行校驗(yàn)。通過defaultProps可以設(shè)置默認(rèn)值,通過propTypes可以規(guī)定屬性的類型。
基本使用示例:
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> ) } } // 規(guī)定屬性的類型-將propTypes設(shè)置成一個(gè)類構(gòu)造函數(shù)屬性 Child.propTypes={ } // 設(shè)置默認(rèn)值 Child.defaultProps = { }
react中單一類型校驗(yàn)器
可以通過PropTypes對(duì)string(字符串)、number(數(shù)字或者是可以被解析成數(shù)字的值)、bool(布爾)、object(對(duì)象)、array(數(shù)組)、func(函數(shù))類型進(jìn)行校驗(yàn)
設(shè)定屬性類型和默認(rèn)值
使用示例:
// 規(guī)定屬性的類型-將propTypes設(shè)置成一個(gè)類構(gòu)造函數(shù)屬性 Child.propTypes = { arrValue: PropTypes.array,//數(shù)組類型 boolValue: PropTypes.bool,//布爾類型 funcValue: PropTypes.func,//函數(shù)類型 numValue: PropTypes.number,//數(shù)字類型 objValue: PropTypes.object,//對(duì)象類型 strValue: PropTypes.string,//字符串類型 } // 設(shè)置默認(rèn)值 Child.defaultProps = { arrValue: [1, 2], boolValue: false, numValue: 0, objValue: { name: 'lisi' }, strValue: '123' }
不傳遞參數(shù)的情況(會(huì)使用設(shè)置的默認(rèn)值):
父類:
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 > ) } }
子類:
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>學(xué)生信息:{`${objValue.name}-${objValue.age}`}</div> <div>得分:{numValue}</div> <div>備注:{strValue}</div> <button onClick={this.printData.bind(this)}>打印</button> </div> ) } } // 規(guī)定屬性的類型-將propTypes設(shè)置成一個(gè)類構(gòu)造函數(shù)屬性 Child.propTypes = { arrValue: PropTypes.array,//數(shù)組類型 boolValue: PropTypes.bool,//布爾類型 funcValue: PropTypes.func,//函數(shù)類型 numValue: PropTypes.number,//數(shù)字類型 objValue: PropTypes.object,//對(duì)象類型 strValue: PropTypes.string,//字符串類型 } // 設(shè)置默認(rèn)值 Child.defaultProps = { arrValue: [1, 2], boolValue: false, numValue: 60, objValue: { name: 'lisi', age: 20 }, strValue: 'xxx' }
傳遞參數(shù)(使用傳遞的值)
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 = '優(yōu)秀' return ( <div> <Child arrValue={arrValue} boolValue={boolValue} numValue={numValue} objValue={objValue} funcValue={this.print} strValue={strValue} ></Child> </div > ) } }
設(shè)置必需屬性
通過isRequired可以設(shè)定屬性是必需的,如果父組件沒有傳遞,并且也沒有默認(rèn)值時(shí)就會(huì)有報(bào)錯(cuò)提醒。
注釋strValue的傳遞
<Child arrValue={arrValue} boolValue={boolValue} numValue={numValue} objValue={objValue} funcValue={this.print} // strValue={strValue} ></Child>
設(shè)置strValue為必需屬性,并注釋默認(rèn)值的設(shè)置
Child.propTypes = { arrValue: PropTypes.array,//數(shù)組類型 boolValue: PropTypes.bool,//布爾類型 funcValue: PropTypes.func,//函數(shù)類型 numValue: PropTypes.number,//數(shù)字類型 objValue: PropTypes.object,//對(duì)象類型 strValue: PropTypes.string.isRequired,//字符串類型 } // 設(shè)置默認(rèn)值 Child.defaultProps = { arrValue: [1, 2], boolValue: false, numValue: 60, objValue: { name: 'lisi', age: 20 }, // strValue: 'xxx' }
運(yùn)行代碼:
放開剛剛注釋掉的默認(rèn)值設(shè)置,發(fā)現(xiàn)不在報(bào)錯(cuò)。
Child.propTypes = { arrValue: PropTypes.array,//數(shù)組類型 boolValue: PropTypes.bool,//布爾類型 funcValue: PropTypes.func,//函數(shù)類型 numValue: PropTypes.number,//數(shù)字類型 objValue: PropTypes.object,//對(duì)象類型 strValue: PropTypes.string.isRequired,//字符串類型 } // 設(shè)置默認(rèn)值 Child.defaultProps = { arrValue: [1, 2], boolValue: false, numValue: 60, objValue: { name: 'lisi', age: 20 }, strValue: 'xxx' }
放開剛剛注釋掉的傳遞strValue設(shè)置,發(fā)現(xiàn)也不會(huì)報(bào)錯(cuò)
<Child arrValue={arrValue} boolValue={boolValue} numValue={numValue} objValue={objValue} funcValue={this.print} strValue={strValue} ></Child>
react中組合類型校驗(yàn)器
組合類型的校驗(yàn)器有如下幾種:
oneOfType:屬性必須是指定的一組類型中的一種
arrayOf:屬性必須是由指定元素組成的數(shù)組
objectOf:屬性必須是一個(gè)帶有指定類型值的屬性值的對(duì)象,也就是說對(duì)象必須要有一個(gè)指定類型的屬性
shape:屬性必須是一個(gè)符合特定格式的對(duì)象,它需要擁有同一組屬性。
node:屬性必須是一個(gè)可以渲染的值:數(shù)字,字符串,元素或數(shù)組
element:屬性必須是一個(gè)React元素
instanceOf:屬性必須是指定類的實(shí)例
oneOf:確保屬性被限制為一組枚舉值中的一項(xiàng)
PropTypes.oneOfType
父類:
const dataValue1 = '測(cè)試'//字符串 const dataValue2 = 234//數(shù)字 const dataValue3 = { name: '王五' }//非字符串和數(shù)字 return ( <div> <Child dataValue1={dataValue1} dataValue2={dataValue2} dataValue3={dataValue3} ></Child> </div > )
子類:
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> ) } } // 規(guī)定屬性的類型-將propTypes設(shè)置成一個(gè)類構(gòu)造函數(shù)屬性 Child.propTypes = { dataValue1: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]), dataValue2: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]), dataValue3: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]) }
可以看到dataValue1和dataValue2都是規(guī)定類型中的一種,可以正常使用;而dataValue3傳遞的不是規(guī)定的類型,就有提醒。
PropTypes.arrayOf
父類:
render() { const dataValue1 = [1, 2, 3, 4]//元素是number類型 const dataValue2 = ['1', '2', '3', '4']//元素是string類型 return ( <div> <Child dataValue1={dataValue1} dataValue2={dataValue2} ></Child> </div > ) }
子類:
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> ) } } // 規(guī)定屬性的類型-將propTypes設(shè)置成一個(gè)類構(gòu)造函數(shù)屬性 Child.propTypes = { dataValue1: PropTypes.arrayOf(PropTypes.number), dataValue2: PropTypes.arrayOf(PropTypes.number), }
可以看到數(shù)組元素是number時(shí)就不沒有錯(cuò)誤提示,但是數(shù)組元素不是number時(shí)就會(huì)有錯(cuò)誤提示。
PropTypes.objectOf
父類:
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 > ) }
子類:
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> ) } } // 規(guī)定屬性的類型-將propTypes設(shè)置成一個(gè)類構(gòu)造函數(shù)屬性 Child.propTypes = { dataValue1: PropTypes.objectOf(PropTypes.number), dataValue2: PropTypes.objectOf(PropTypes.number), }
PropTypes.shape
父類:
render() { const dataValue1 = { name: '張三', age: 20 } const dataValue2 = { name: '張三', age: "20"http://age不傳遞number類型 } const dataValue3 = { name: '張三',//少傳遞一個(gè)屬性 } const dataValue4 = { name: '張三', age: 20, num: 88,//多傳遞一個(gè)屬性 } return ( <div> <Child dataValue1={dataValue1} dataValue2={dataValue2} dataValue3={dataValue3} dataValue4={dataValue4} ></Child> </div > ) }
子類:
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> ) } } // 規(guī)定屬性的類型-將propTypes設(shè)置成一個(gè)類構(gòu)造函數(shù)屬性 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 }), }
由此可見,缺少屬性或者增加屬性都不會(huì)有錯(cuò)誤提醒,但是如果傳遞的屬性類型跟預(yù)定的不一致就會(huì)有錯(cuò)誤提醒。
PropTypes.node
父組件:
render() { const dataValue1 = 123//數(shù)字 const dataValue2 = '張三'//字符串 const dataValue3 = [1, 2, 3] const dataValue4 = {//對(duì)象 name: '張三', age: 20, num: 88, } return ( <div> <Child dataValue1={dataValue1} dataValue2={dataValue2} dataValue3={dataValue3} dataValue4={dataValue4} ></Child> </div > ) }
子組件:
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> ) } } // 規(guī)定屬性的類型-將propTypes設(shè)置成一個(gè)類構(gòu)造函數(shù)屬性 Child.propTypes = { dataValue1: PropTypes.node, dataValue2: PropTypes.node, dataValue3: PropTypes.node, dataValue4: PropTypes.node, }
可以看到當(dāng)預(yù)定屬性為PropTypes.node類型時(shí),可以傳遞數(shù)字,字符串,數(shù)組,但是傳遞對(duì)象類型時(shí)就會(huì)有報(bào)錯(cuò)提示。注意PropTypes.node類型并不僅僅局限于數(shù)字,字符串,數(shù)組,還可以是其他任何可渲染的元素。
Vue中的props驗(yàn)證
vue中可以對(duì)如下類型進(jìn)行檢查:String、Number、Boolean、Array、Object、Date、Function、Symbol以及自定義類型。
vue數(shù)據(jù)驗(yàn)證:通過變量名:具體類型的方法
父組件:
<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>
子組件:
<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數(shù)據(jù)驗(yàn)證:帶有默認(rèn)值的方式驗(yàn)證
vue中設(shè)置默認(rèn)值是使用default屬性,此時(shí)設(shè)置數(shù)據(jù)類型時(shí)需要使用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: { // 設(shè)置類型 type: String, // 設(shè)置默認(rèn)值 default: "XXX", }, age: { type: Number, default: 0, }, obj: { type: Object, // 注意:對(duì)象和數(shù)組的默認(rèn)值必須從一個(gè)工廠函數(shù)獲取 default: function () { return { name: "xxxx", age: -1, }; }, }, obj2: { func: Function, }, }, data() { return {}; }, methods: {}, }; </script>
注意:對(duì)象和數(shù)組的默認(rèn)值必須從一個(gè)工廠函數(shù)獲取。
通過required設(shè)置必須屬性
name: { // 設(shè)置類型 type: String, // 設(shè)置默認(rèn)值 default: "XXX", // 通過required設(shè)置必須屬性 required: true, },
通過required設(shè)置name為必需屬性之后,如果沒有傳遞name字段,就會(huì)有錯(cuò)誤提示。
多種類型中的一種
<template> <div>數(shù)據(jù)驗(yàn)證</div> </template> <script> export default { name: "PropsChildDemo", components: {}, props: { info: [String, Number, Boolean], }, data() { return {}; }, }; </script>
info必須為String,Number,Boolean中的一種,否則就會(huì)有提示。
傳遞了一個(gè)對(duì)象:
<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>
傳遞一個(gè)字符串:
<template> <div> <PropsChildDemo :info="info"></PropsChildDemo> </div> </template> <script> import PropsChildDemo from "./PropsChildDemo.vue"; export default { name: "PropsDemo", components: { PropsChildDemo }, data() { return { info: "張三", }; }, }; </script>
對(duì)象數(shù)組驗(yàn)證,并且數(shù)組元素是特定屬性的對(duì)象
驗(yàn)證info是一個(gè)數(shù)組,并且數(shù)組元素是由name,age屬性組成的對(duì)象
<template> <div>數(shù)據(jù)驗(yàn)證</div> </template> <script> export default { name: "PropsChildDemo", components: {}, props: { info: { // 設(shè)置必須 required: true, type: Array, // 驗(yàn)證info是一個(gè)數(shù)組,并且數(shù)組元素是由name,age屬性組成的對(duì)象 validator(value) { return value.every((item) => { const { name, age } = item; return Boolean(name && age); }); }, }, }, data() { return {}; }, }; </script>
少傳一個(gè)屬性:
<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, }, // 其中一個(gè)元素少一個(gè)屬性 { name: "wangwu", }, ], }; }, }; </script>
按要求傳遞:
<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>
多傳遞一個(gè)參數(shù):
<template> <div> <PropsChildDemo :info="info"></PropsChildDemo> </div> </template> <script> import PropsChildDemo from "./PropsChildDemo.vue"; export default { name: "PropsDemo", components: { PropsChildDemo }, data() { return { info: [ // 多傳遞一個(gè)參數(shù) { name: "zhangsan", age: 20, num: 88, }, ], }; }, }; </script>
所以少傳或者錯(cuò)傳都會(huì)驗(yàn)證失敗,多傳或者按要求傳遞能驗(yàn)證通過。
自定義驗(yàn)證函數(shù)
<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必須為zhangsan,lisi,wangwu中的一個(gè),否則就會(huì)有錯(cuò)誤提示
傳遞zhangsan,lisi,wangwu中的一個(gè),就不會(huì)有錯(cuò)誤提示:
<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>
到此這篇關(guān)于React和Vue的props驗(yàn)證的文章就介紹到這了,更多相關(guān)Vue props驗(yàn)證內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React實(shí)現(xiàn)動(dòng)效彈窗組件
最近在使用react開發(fā)項(xiàng)目,遇到這樣一個(gè)需求實(shí)現(xiàn)一個(gè)帶有動(dòng)效的 React 彈窗組件,如果不考慮動(dòng)效,很容易實(shí)現(xiàn),接下來小編通過本文給大家介紹React實(shí)現(xiàn)動(dòng)效彈窗組件的實(shí)現(xiàn)代碼,一起看看吧2021-06-06React?Fiber?樹思想解決業(yè)務(wù)實(shí)際場(chǎng)景詳解
這篇文章主要為大家介紹了React?Fiber?樹思想解決業(yè)務(wù)實(shí)際場(chǎng)景詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12ReactRouterV6如何獲取當(dāng)前路由參數(shù)
這篇文章主要介紹了ReactRouterV6如何獲取當(dāng)前路由參數(shù)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03在create-react-app中使用css modules的示例代碼
這篇文章主要介紹了在create-react-app中使用css modules的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07