您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Drawer.js 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // @flow
  2. import React, { useEffect, useRef } from 'react';
  3. type Props = {
  4. /**
  5. * The component(s) to be displayed within the drawer menu.
  6. */
  7. children: React$Node,
  8. /**
  9. * Whether the drawer should be shown or not.
  10. */
  11. isOpen: boolean,
  12. /**
  13. * Function that hides the drawer.
  14. */
  15. onClose: Function
  16. };
  17. /**
  18. * Component that displays the mobile friendly drawer on web.
  19. *
  20. * @returns {ReactElement}
  21. */
  22. function Drawer({
  23. children,
  24. isOpen,
  25. onClose }: Props) {
  26. const drawerRef: Object = useRef(null);
  27. /**
  28. * Closes the drawer when clicking or touching outside of it.
  29. *
  30. * @param {Event} event - Mouse down/start touch event object.
  31. * @returns {void}
  32. */
  33. function handleOutsideClickOrTouch(event: Event) {
  34. if (drawerRef.current && !drawerRef.current.contains(event.target)) {
  35. onClose();
  36. }
  37. }
  38. useEffect(() => {
  39. window.addEventListener('mousedown', handleOutsideClickOrTouch);
  40. window.addEventListener('touchstart', handleOutsideClickOrTouch);
  41. return () => {
  42. window.removeEventListener('mousedown', handleOutsideClickOrTouch);
  43. window.removeEventListener('touchstart', handleOutsideClickOrTouch);
  44. };
  45. }, [ drawerRef ]);
  46. return (
  47. isOpen ? (
  48. <div
  49. className = 'drawer-menu'
  50. ref = { drawerRef }>
  51. {children}
  52. </div>
  53. ) : null
  54. );
  55. }
  56. export default Drawer;