Перейти к контенту

Прослушиватель завершающего щелчка

Detect if a click event happened outside of an element. It listens for clicks that occur somewhere in the document.

Пример

Например, если вам нужно скрыть выпадающее меню щелчком по странице за его пределами:

<ClickAwayListener onClickAway={handleClickAway}>
  <Box sx={{ position: 'relative' }}>
    <button type="button" onClick={handleClick}>
      Open menu dropdown
    </button>
    {open ? (
      <Box sx={styles}>
        Click me, I will stay visible until you click outside.
      </Box>
    ) : null}
  </Box>
</ClickAwayListener>

Notice that the component only accepts one child element. You can find a more advanced demo on the Menu documentation section.

Portal

The following demo uses Portal to render the dropdown into a new "subtree" outside of current DOM hierarchy.

<ClickAwayListener onClickAway={handleClickAway}>
  <div>
    <button type="button" onClick={handleClick}>
      Open menu dropdown
    </button>
    {open ? (
      <Portal>
        <Box sx={styles}>
          Click me, I will stay visible until you click outside.
        </Box>
      </Portal>
    ) : null}
  </div>
</ClickAwayListener>

Leading edge

By default, the component responds to the trailing events (click + touch end). However, you can configure it to respond to the leading events (mouse down + touch start).

<ClickAwayListener
  mouseEvent="onMouseDown"
  touchEvent="onTouchStart"
  onClickAway={handleClickAway}
>
  <Box sx={{ position: 'relative' }}>
    <button type="button" onClick={handleClick}>
      Open menu dropdown
    </button>
    {open ? (
      <Box sx={styles}>
        Click me, I will stay visible until you click outside.
      </Box>
    ) : null}
  </Box>
</ClickAwayListener>

⚠️ In this mode, only interactions on the scrollbar of the document is ignored.