Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

OutsideClickHandler.tsx 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. import * as React from 'react';
  21. import { findDOMNode } from 'react-dom';
  22. interface Props {
  23. children: React.ReactNode;
  24. onClickOutside: () => void;
  25. }
  26. export default class OutsideClickHandler extends React.Component<Props> {
  27. mounted = false;
  28. componentDidMount() {
  29. this.mounted = true;
  30. setTimeout(() => {
  31. this.addClickHandler();
  32. }, 0);
  33. }
  34. componentWillUnmount() {
  35. this.mounted = false;
  36. this.removeClickHandler();
  37. }
  38. addClickHandler = () => {
  39. window.addEventListener('click', this.handleWindowClick);
  40. };
  41. removeClickHandler = () => {
  42. window.removeEventListener('click', this.handleWindowClick);
  43. };
  44. handleWindowClick = (event: MouseEvent) => {
  45. if (this.mounted) {
  46. // eslint-disable-next-line react/no-find-dom-node
  47. const node = findDOMNode(this);
  48. if (!node || !node.contains(event.target as Node)) {
  49. this.props.onClickOutside();
  50. }
  51. }
  52. };
  53. render() {
  54. return this.props.children;
  55. }
  56. }