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

🎉 Material UI v5 is out! Head to the migration guide to get started.

Всплывающий компонент

Всплывающие компоненты показывают краткие сообщения о процессах приложения. The component is also known as a toast.

Snackbars inform users of a process that an app has performed or will perform. Они времени отображаются в нижней части экрана (данное поведение можно изменить). Они не должны прерывать использование приложения пользователем, и они не требуют никаких действий для их закрытия.

Всплывающие компоненты содержат одну строку текста, непосредственно связанную с выполненной операцией. Они могут содержать текстовое действие, но не иконки. Вы можете использовать их для отображения уведомлений.

Количество на странице

В один момент на странице можно отобразить только один всплывающий компонент.

Простые всплывающие компоненты

A basic snackbar that aims to reproduce Google Keep's snackbar behavior.

Customized snackbars

Ниже находятся примеры кастомизации компонента. You can learn more about this in the overrides documentation page.

<Button variant="outlined" onClick={handleClick}>
  Open success snackbar
</Button>
<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
  <Alert onClose={handleClose} severity="success">
    This is a success message!
  </Alert>
</Snackbar>
<Alert severity="error">This is an error message!</Alert>
<Alert severity="warning">This is a warning message!</Alert>
<Alert severity="info">This is an information message!</Alert>
<Alert severity="success">This is a success message!</Alert>

Позиционированные всплывающие уведомления

In wide layouts, snackbars can be left-aligned or center-aligned if they are consistently placed on the same spot at the bottom of the screen, however there may be circumstances where the placement of the snackbar needs to be more flexible. You can control the position of the snackbar by specifying the anchorOrigin prop.

{buttons}
<Snackbar
  anchorOrigin={{ vertical, horizontal }}
  open={open}
  onClose={handleClose}
  message="I love snacks"
  key={vertical + horizontal}
/>

Длина сообщения

Some snackbars with varying message length.

<SnackbarContent message="I love snacks." action={action} />
<SnackbarContent
  message={
    'I love candy. I love cookies. I love cupcakes. \
    I love cheesecake. I love chocolate.'
  }
/>
<SnackbarContent message="I love candy. I love cookies. I love cupcakes." action={action} />
<SnackbarContent
  message={
    'I love candy. I love cookies. I love cupcakes. \
    I love cheesecake. I love chocolate.'
  }
  action={action}
/>

Transições

Consecutive Snackbars

When multiple snackbar updates are necessary, they should appear one at a time.

Snackbars and floating action buttons (FABs)

Snackbars should appear above FABs (on mobile).

Изменение анимации

Увеличение - это анимация, которая используется по умолчанию, но вы можете использовать другую анимацию.

<Button onClick={handleClick(GrowTransition)}>Grow Transition</Button>
<Button onClick={handleClick(Fade)}>Fade Transition</Button>
<Button onClick={handleClick(SlideTransition)}>Slide Transition</Button>
<Snackbar
  open={state.open}
  onClose={handleClose}
  TransitionComponent={state.Transition}
  message="I love snacks"
  key={state.Transition.name}
/>

Control Slide direction

Вы можете изменить направление анимации.

<Button onClick={handleClick(TransitionLeft)}>Right</Button>
<Button onClick={handleClick(TransitionUp)}>Up</Button>
<Button onClick={handleClick(TransitionRight)}>Left</Button>
<Button onClick={handleClick(TransitionDown)}>Down</Button>
<Snackbar
  open={open}
  onClose={handleClose}
  TransitionComponent={transition}
  message="I love snacks"
  key={transition ? transition.name : ''}
/>

Дополнительные проекты

Для более сложных вариантов использования вы можете воспользоваться:

notistack

stars npm downloads

This example demonstrates how to use notistack. notistack has an imperative API that makes it easy to display snackbars, without having to handle their open/close state. It also enables you to stack them on top of one another (although this is discouraged by the Material Design specification).

Доступность

(WAI-ARIA: https://www.w3.org/TR/wai-aria-1.1/#alert)

  • По умолчанию всплывающий компонент не будет скрываться автоматически. Однако, если вы решите использовать функцию autoHideDuration, рекомендуется дать пользователю достаточное время для реагирования.