React cloneElement 函数详解:克隆 React 元素
function cloneElement(element, config, children) {
if (element === null || element === undefined) {
throw new Error(
React.cloneElement(...): The argument must be a React element, but you passed ${element}.
);
}
let propName;
// Original props are copied const props = Object.assign({}, element.props);
// Reserved names are extracted let key = element.key; let ref = element.ref; // Self is preserved since the owner is preserved. const self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. const source = element._source;
// Owner will be preserved, unless ref is overridden let owner = element._owner;
if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { if (DEV) { checkKeyStringCoercion(config.key); } key = '' + config.key; }
// Remaining properties override existing props
let defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (
hasOwnProperty.call(config, propName) &&
!RESERVED_PROPS.hasOwnProperty(propName)
) {
if (config[propName] === undefined && defaultProps !== undefined) {
// Resolve default props
props[propName] = defaultProps[propName];
} else {
props[propName] = config[propName];
}
}
}
}
// Children can be more than one argument, and those are transferred onto // the newly allocated props object. const childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { const childArray = Array(childrenLength); for (let i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; }
return ReactElement(element.type, key, ref, self, source, owner, props); }
// 函数功能 这个函数的功能是克隆一个React元素,并根据传入的配置和子元素,返回一个新的React元素。
原文地址: https://www.cveoy.top/t/topic/qlxY 著作权归作者所有。请勿转载和采集!