1.Angular
1.1.使用FormControl,Validators
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-example',
template: `
<input [formControl]="nameControl">
<div *ngIf="nameControl.errors && nameControl.dirty">
<div *ngIf="nameControl.errors.required">Name is required.</div>
</div>
`
})
export class ExampleComponent {
nameControl = new FormControl('', [Validators.required]);
}
1.2.自定义验证器
import { Directive } from '@angular/core';
import { Validator, AbstractControl, ValidationErrors } from '@angular/forms';
@Directive({
selector: '[appCustomValidator]',
providers: [{provide: Validator, useExisting: CustomValidatorDirective, multi: true}]
})
export class CustomValidatorDirective implements Validator {
validate(control: AbstractControl): ValidationErrors | null {
const value = control.value;
// 自定义验证逻辑
if (value === 'invalid') {
return { custom: true };
}
return null; // 如果没有错误,返回null
}
}
1.3.在组件类中,你可以使用@Input装饰器来接收属性,并通过setter方法来进行验证。
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-example',
template: `...`
})
export class ExampleComponent {
private _name: string;
@Input() set name(value: string) {
if (!value) {
console.error('Name is required');
return; // 或者抛出错误,例如 throw new Error('Name is required');
}
this._name = value;
}
}
2.Vue
在 Vue 2.x 中,你可以在组件的 props 选项中使用验证函数来定义每个 prop 的验证规则。
Vue.component('my-component', {
props: {
// 基础类型检查
propA: Number,
// 多个可能的类型
propB: [String, Number],
// 必填的字符串
propC: {
type: String,
required: true
},
// 带有默认值的数字
propD: {
type: Number,
default: 100
},
// 带有默认值的对象
propE: {
type: Object,
// 对象或数组默认值必须从一个工厂函数获取
default: function () {
return { message: 'hello' }
}
},
// 自定义验证函数
propF: {
validator: function (value) {
// 这个值必须匹配下列字符串中的一个
return ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
},
// ...
})
在 Vue 3.x 中,如果你使用 TypeScript,可以利用 TypeScript 的类型系统来进行更强大的 prop 验证。这不仅可以避免 JavaScript 的运行时错误,还可以在编译阶段捕获类型错误。
import { defineComponent, PropType } from 'vue';
export default defineComponent({
props: {
propA: {
type: Number as PropType<number>,
required: true,
},
propB: {
type: [String, Number] as PropType<string | number>,
default: 'default string',
},
propC: {
type: Object as PropType<{ message: string }>,
default: () => ({ message: 'hello' }),
},
propF: {
type: String as PropType<'success' | 'warning' | 'danger'>,
validator: (value: string) => ['success', 'warning', 'danger'].includes(value),
},
},
// ...
});
3.Reat
从React v15.5开始,React官方推荐使用prop-types库来进行props验证。
安装
npm install prop-types --save
或者
yarn add prop-types
3.1.对类组件使用prop-types进行属性验证
import React from 'react';
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
render() {
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.props.content}</p>
</div>
);
}
}
// 使用prop-types进行属性验证
MyComponent.propTypes = {
// 指定title为字符串类型,且为必传属性
title: PropTypes.string.isRequired,
// 指定content为字符串类型,且非必传属性,有默认值
content: PropTypes.string,
// 指定一个自定义类型,例如一个数字范围
age: PropTypes.number, // 没有指定isRequired,所以是可选的
// 指定一个对象类型,对象内部可以有多个字段的验证
user: PropTypes.shape({
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
}),
// 指定一个数组类型,数组内的元素可以是字符串类型
tags: PropTypes.arrayOf(PropTypes.string),
// 指定一个元素类型,可以是React元素类型或类组件类型
element: PropTypes.element, // 可以是任何React元素,如 <div /> 或 <MyComponent />
// 指定一个枚举类型,只能是特定的几个值之一
status: PropTypes.oneOf(['active', 'inactive', 'deleted']),
// 指定一个函数类型
doSth: PropTypes.func
};
// 设置默认属性值(可选)
MyComponent.defaultProps = {
content: '默认内容',
age: 30 // 默认年龄为30,如果未提供age属性时使用此值
};
export default MyComponent;
作为一个更喜欢面向对象的开发思路的开发人员,就很希望能够把MyComponent.propTypes和MyComponent.defaultProps定义在MyComponent类里面,可以使用static关键字来做到这一点。
不加static则属性是定义在实例对象上,使用static则属性是定义在原型对象上。
class MyComponent extends React.Component {
static propTypes = xxxx
static defaultProps = xxxx
}
3.2.对函数组件使用prop-types进行属性验证
接收props作为参数,其他写法与把propTypes写在类外面时的写法一样
function MyComponent(props) {
const {name,age,xxx} = props
return (
<ul>
<li>{name}</li>
</ul>
)
}
MyComponent.propTypes = {
xxxxxxxx
}