跳到主要内容

React DOM option

一、作用

二、验证选项属性

备注
/**
* Implements an <option> host component that warns when `selected` is set.
*
* 实现了一个 `<option>` 宿主组件,当设置 `selected` 时会发出警告。
*/

export function validateOptionProps(element: Element, props: Object) {
if (__DEV__) {
// If a value is not provided, then the children must be simple.
// 如果没有提供值,则子元素必须是简单的。
if (props.value == null) {
if (typeof props.children === 'object' && props.children !== null) {
Children.forEach(props.children, function (child) {
if (child == null) {
return;
}
if (
typeof child === 'string' ||
typeof child === 'number' ||
typeof child === 'bigint'
) {
return;
}
if (!didWarnInvalidChild) {
didWarnInvalidChild = true;
console.error(
'Cannot infer the option value of complex children. ' +
'Pass a `value` prop or use a plain string as children to <option>.',
);
}
});
} else if (props.dangerouslySetInnerHTML != null) {
if (!didWarnInvalidInnerHTML) {
didWarnInvalidInnerHTML = true;
console.error(
'Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' +
'which value should be selected.',
);
}
}
}

// TODO: Remove support for `selected` in <option>.
// 待办:移除 `<option>` 中对 `selected` 的支持。
if (props.selected != null && !didWarnSelectedSetOnOption) {
console.error(
'Use the `defaultValue` or `value` props on <select> instead of ' +
'setting `selected` on <option>.',
);
didWarnSelectedSetOnOption = true;
}
}
}

变量

1. 已警告所选集合的选项

// 已警告所选集合的选项
let didWarnSelectedSetOnOption = false;
// 警告无效子元素
let didWarnInvalidChild = false;
// 已警告无效的 innerHTML
let didWarnInvalidInnerHTML = false;