reactUtils.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // https://stackoverflow.com/questions/33199959/how-to-detect-a-react-component-vs-a-react-element
  2. import React from 'react';
  3. import { isHTMLElement } from '@douyinfe/semi-foundation/utils/dom';
  4. function isClassComponent(component: any) {
  5. return typeof component === 'function' && Boolean(component.prototype.isReactComponent);
  6. }
  7. function isFunctionalComponent(Component: any) {
  8. return (
  9. typeof Component === 'function' && // can be various things
  10. !(
  11. Component.prototype && Component.prototype.isReactComponent // native arrows don't have prototypes
  12. )
  13. );
  14. }
  15. function isReactComponent(component: any) {
  16. return isClassComponent(component) || isFunctionalComponent(component);
  17. }
  18. function isElement(element: any) {
  19. return React.isValidElement(element);
  20. }
  21. function isCompositeTypeElement(element: any) {
  22. return isElement(element) && typeof element.type === 'function';
  23. }
  24. function isEmptyChildren(children: any) {
  25. return React.Children.count(children) === 0;
  26. }
  27. export {
  28. isClassComponent,
  29. isFunctionalComponent,
  30. isReactComponent,
  31. isElement,
  32. // isDOMTypeElement,
  33. isHTMLElement,
  34. isCompositeTypeElement,
  35. isEmptyChildren
  36. };