React DOM invalid ARI hook
一、作用
二、验证属性
export function validateProperties(type, props) {
if (__DEV__) {
const invalidProps = [];
for (const key in props) {
const isValid = validateProperty(type, key);
if (!isValid) {
invalidProps.push(key);
}
}
const unknownPropString = invalidProps
.map(prop => '`' + prop + '`')
.join(', ');
if (invalidProps.length === 1) {
console.error(
'Invalid aria prop %s on <%s> tag. ' +
'For details, see https://react.dev/link/invalid-aria-props',
unknownPropString,
type,
);
} else if (invalidProps.length > 1) {
console.error(
'Invalid aria props %s on <%s> tag. ' +
'For details, see https://react.dev/link/invalid-aria-props',
unknownPropString,
type,
);
}
}
}
三、常量
1. 已警告的属性
// 已警告的属性
const warnedProperties = {};
// aria 属性正则
const rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
// aria 驼峰(camel hump)正则
const rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
四、工具
1. 验证属性
备注
hasOwnProperty()由 hasOwnProperty 实现validAriaProperties由 validAriaProperties#validAriaProperties 提供
function validateProperty(tagName, name) {
if (__DEV__) {
if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
return true;
}
if (rARIACamel.test(name)) {
const ariaName = 'aria-' + name.slice(4).toLowerCase();
const correctName = validAriaProperties.hasOwnProperty(ariaName)
? ariaName
: null;
// If this is an aria-* attribute, but is not listed in the known DOM
// DOM properties, then it is an invalid aria-* attribute.
// 如果这是一个 aria-* 属性,但未在已知 DOM 属性中列出,则它是无效的 aria-*
// 属性。
if (correctName == null) {
console.error(
'Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.',
name,
);
warnedProperties[name] = true;
return true;
}
// aria-* attributes should be lowercase; suggest the lowercase version.
// aria-* 属性应为小写;建议使用小写版本。
if (name !== correctName) {
console.error(
'Invalid ARIA attribute `%s`. Did you mean `%s`?',
name,
correctName,
);
warnedProperties[name] = true;
return true;
}
}
if (rARIA.test(name)) {
const lowerCasedName = name.toLowerCase();
const standardName = validAriaProperties.hasOwnProperty(lowerCasedName)
? lowerCasedName
: null;
// If this is an aria-* attribute, but is not listed in the known DOM
// DOM properties, then it is an invalid aria-* attribute.
// 如果这是一个 aria-* 属性,但未在已知 DOM 属性中列出,则它是无效的 aria-* 属性。
if (standardName == null) {
warnedProperties[name] = true;
return false;
}
// aria-* attributes should be lowercase; suggest the lowercase version.
// aria-* 属性应为小写;建议使用小写版本。
if (name !== standardName) {
console.error(
'Unknown ARIA attribute `%s`. Did you mean `%s`?',
name,
standardName,
);
warnedProperties[name] = true;
return true;
}
}
}
return true;
}