export default function forwardRef<Props, ElementType: React$ElementType>(
render: (props: Props, ref: React$Ref<ElementType>) => React$Node,
) {
// 开发环境校验报错
if (__DEV__) {
// 如果封装的不是函数,则抛出错误
if (typeof render !== 'function') {
warningWithoutStack(
false,
'forwardRef requires a render function but was given %s.',
render === null ? 'null' : typeof render,
);
} else {
// 如果对应组件的入参只有一个或者超出两个则抛出错误,正常 forwardRef 的组件应该有两个入参 (props, ref)
warningWithoutStack(
// Do not warn for 0 arguments because it could be due to usage of the 'arguments' object
// 如果没有入参可能是内部使用了 arguments 来获取入参,所以不抛出错误
render.length === 0 || render.length === 2,
'forwardRef render functions accept exactly two parameters: props and ref. %s',
render.length === 1
? 'Did you forget to use the ref parameter?'
: 'Any additional parameter will be undefined.',
);
}
if (render != null) {
// 由于 forwardRef 不支持类组件所以如果发现对应情况,则抛出错误
warningWithoutStack(
render.defaultProps == null && render.propTypes == null,
'forwardRef render functions do not support propTypes or defaultProps. ' +
'Did you accidentally pass a React component?',
);
}
}
// 返回一个 React Forward Ref Type 类型的 React 元素
return {
$$typeof: REACT_FORWARD_REF_TYPE,
render,
};
}