JGuang

轻提示

Snackbar · Material UI

交互预览
npm install @mui/material@9.4.0 @emotion/react@11.14.0 @emotion/styled@11.14.1

轻提示

在不中断主要任务的情况下展示短暂反馈。

本指南覆盖默认 Emotion 环境的 Material UI Core;扩展包与额外示例按清单单独标注。

使用场景与业务边界

计时器只请求关闭,宿主须更新 open;通知不实现队列、撤销或后端成功判定。

原生组成与范围

Snackbar, SnackbarContent

保持 Material UI 原生组合与类型,不替换为 JGuang/Base UI/Radix 同名 API。示例条目不是额外组件。

原生安装与初始化

npm install @mui/material@9.4.0 @emotion/react@11.14.0 @emotion/styled@11.14.1

采用原生 npm 包与 Emotion,不提供虚构的 JGuang UI Registry 地址。将示例放在原生 ThemeProvider 内,按项目选择 CssBaseline 或 ScopedCssBaseline。先检查 React、现有 Provider、锁文件与 SSR 配置;不要覆盖用户文件或忽略 peer 冲突。本批实际验收 React 19.2.8;React 18 及以下须匹配 react-is。完整初始化规则见随附的双语 setup 文档。

关键原生参数

仅解释本指南选出的关键参数,不是平铺的通用 API。原生继承来源、slot 结构、可空值与泛型仍按固定源码保留。

所属组件.属性用途说明声明来源
Snackbar.open受控原生可见性,不获取数据或执行操作。Snackbar
Snackbar.onClose原生关闭请求,reason/event 签名因组件不同,宿主须更新 open。Snackbar
Snackbar.autoHideDuration原生 Snackbar 请求关闭前的毫秒数,宿主须更新 open。Snackbar
Snackbar.anchorOrigin原生垂直/水平方向的锚点组合。Snackbar
Snackbar.message宿主提供的 Snackbar 消息,不是自动生成的后端结果。Snackbar

可运行原生示例

下列机器键只选择示例入口,不会作为通用 variant 属性传入每个组件。原生示例 JSX 与数据保持上游原文;JGuang 编写的验收示例明确标注。

  • 基础介绍 · SimpleSnackbar · 上游原生示例
  • 位置 · PositionedSnackbar · 上游原生示例
  • 内容 · LongTextSnackbar · 上游原生示例
  • 自动关闭 · AutohideSnackbar · 上游原生示例
  • 多种过渡动画 · TransitionsSnackbar · 上游原生示例
  • 搭配提示信息 · CustomizedSnackbars · 上游原生示例
  • 搭配悬浮操作按钮 · FabIntegrationSnackbar · 上游原生示例
  • 连续轻提示 · ConsecutiveSnackbars · 上游原生示例

尚未支持的额外示例

这些条目仍保留在上游清单中,不静默跳过,也不展示为已完成预览。需要补充依赖/框架验收后再纳入可运行列表。

  • 额外通知队列库 · IntegrationNotistack: notistack

真实使用示例

固定版本的未修改原生示例;复制时同时保留所需的局部辅助文件。

import * as React from 'react';
import Button from '@mui/material/Button';
import Snackbar, { SnackbarCloseReason } from '@mui/material/Snackbar';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';

export default function SimpleSnackbar() {
  const [open, setOpen] = React.useState(false);

  const handleClick = () => {
    setOpen(true);
  };

  const handleClose = (
    event: React.SyntheticEvent | Event,
    reason?: SnackbarCloseReason,
  ) => {
    if (reason === 'clickaway') {
      return;
    }

    setOpen(false);
  };

  const action = (
    <React.Fragment>
      <Button color="secondary" size="small" onClick={handleClose}>
        UNDO
      </Button>
      <IconButton
        size="small"
        aria-label="close"
        color="inherit"
        onClick={handleClose}
      >
        <CloseIcon fontSize="small" />
      </IconButton>
    </React.Fragment>
  );

  return (
    <div>
      <Button onClick={handleClick}>Open Snackbar</Button>
      <Snackbar
        open={open}
        autoHideDuration={6000}
        onClose={handleClose}
        message="Note archived"
        action={action}
      />
    </div>
  );
}

示例依赖边界

react, @mui/material/Button, @mui/material/Snackbar, @mui/material/IconButton, @mui/icons-material/Close, @mui/material/Grid, @mui/material/Box, @mui/material/Stack, @mui/material/SnackbarContent, @mui/material/Fade, @mui/material/Slide, @mui/material/Grow, @mui/material/transitions, @mui/material/Alert, @mui/material/AppBar, @mui/material/CssBaseline, @mui/material/GlobalStyles, @mui/material/Toolbar, @mui/icons-material/Menu, @mui/material/Typography, @mui/material/Fab, @mui/icons-material/Add

直接导入 Icons/System/Utils 的示例需要匹配 9.4.0 包。局部数据与辅助文件属于示例闭包,不是额外组件。远程图片和模拟操作不提供后端。

固定上游 API 元数据参考

以下表格保留上游元数据,不是重新推断的通用类型体系。条件泛型、继承属性与回调细节以以下源码声明为准。主题默认配置可能覆盖元数据默认值。

Snackbar

import Snackbar from '@mui/material/Snackbar';
import { Snackbar } from '@mui/material';
属性必需上游元数据类型/约束元数据默认值
action否node—
anchorOrigin否{ horizontal: 'center' | 'left' | 'right', vertical: 'bottom' | 'top' }{ vertical: 'bottom', horizontal: 'left' }
autoHideDuration否numbernull
children否element—
classes否object—
disableWindowBlurListener否boolfalse
key否any—
message否node—
onClose否func—
open否bool—
resumeHideDuration否number—
slotProps否{ clickAwayListener?: func | object, content?: func | object, root?: func | object, transition?: func | object }{}
slots否{ clickAwayListener?: elementType, content?: elementType, root?: elementType, transition?: elementType }{}
sx否Array<func | object | bool> | func | object—
transitionDuration否number | { appear?: number, enter?: number, exit?: number }{ enter: theme.transitions.duration.enteringScreen, exit: theme.transitions.duration.leavingScreen, }

SnackbarContent

import SnackbarContent from '@mui/material/SnackbarContent';
import { SnackbarContent } from '@mui/material';

原生继承: Paper. 父级与 DOM 属性未被伪造为本组件新属性。

属性必需上游元数据类型/约束元数据默认值
action否node—
classes否object—
message否node—
role否string'alert'
sx否Array<func | object | bool> | func | object—

原生源码声明

声明与 import 从固定源码提取,不平铺联合类型或外部继承。英文注释/类型属于原始源码参考,不代表上游正文已全文翻译。共享类型仍位于原生包中。

vendor/src/Snackbar/Snackbar.d.ts

import * as React from 'react';

import { SxProps } from '@mui/system';

import ClickAwayListener from '../ClickAwayListener';

import { Theme } from '../styles';

import { InternalStandardProps as StandardProps } from '../internal';

import { SnackbarContentProps } from '../SnackbarContent';

import { TransitionProps } from '../transitions/types';

import { SnackbarClasses } from './snackbarClasses';

import { CreateSlotsAndSlotProps, SlotComponentProps, SlotProps } from '../utils/types';

export interface SnackbarSlots {
  /**
   * The component that renders the root slot.
   * @default 'div'
   */
  root: React.ElementType;
  /**
   * The component that renders the content slot.
   * @default SnackbarContent
   */
  content: React.ElementType;
  /**
   * The component that renders the clickAwayListener slot.
   * @default ClickAwayListener
   */
  clickAwayListener: React.ElementType;
  /**
   * The component that renders the transition.
   * [Follow this guide](/material-ui/transitions/#transition-slots) to learn more about the requirements for this component.
   * @default Grow
   */
  transition: React.ElementType;
}

export interface SnackbarRootSlotPropsOverrides {}

export interface SnackbarContentSlotPropsOverrides {}

export interface SnackbarClickAwayListenerSlotPropsOverrides {}

export interface SnackbarTransitionSlotPropsOverrides {}

export type SnackbarSlotsAndSlotProps = CreateSlotsAndSlotProps<
  SnackbarSlots,
  {
    /**
     * Props forwarded to the root slot.
     * By default, the available props are based on the div element.
     */
    root: SlotProps<'div', SnackbarRootSlotPropsOverrides, SnackbarOwnerState>;
    /**
     * Props forwarded to the content slot.
     * By default, the available props are based on the [SnackbarContent](https://mui.com/material-ui/api/snackbar-content/#props) component.
     */
    content: SlotProps<
      React.ElementType<SnackbarContentProps>,
      SnackbarContentSlotPropsOverrides,
      SnackbarOwnerState
    >;
    /**
     * Props forwarded to the clickAwayListener slot.
     * By default, the available props are based on the [ClickAwayListener](https://mui.com/material-ui/api/click-away-listener/#props) component.
     */
    clickAwayListener: SlotComponentProps<
      typeof ClickAwayListener,
      SnackbarClickAwayListenerSlotPropsOverrides,
      SnackbarOwnerState
    >;
    /**
     * Props applied to the transition element.
     * By default, the element is based on the [Grow](https://mui.com/material-ui/api/grow/#props) component.
     */
    transition: SlotComponentProps<
      React.ElementType<TransitionProps>,
      TransitionProps & SnackbarTransitionSlotPropsOverrides,
      SnackbarOwnerState
    >;
  }
>;

export interface SnackbarOrigin {
  vertical: 'top' | 'bottom';
  horizontal: 'left' | 'center' | 'right';
}

export type SnackbarCloseReason = 'timeout' | 'clickaway' | 'escapeKeyDown';

export interface SnackbarProps
  extends
    Omit<StandardProps<React.HTMLAttributes<HTMLDivElement>>, 'slots' | 'slotProps'>,
    SnackbarSlotsAndSlotProps {
  /**
   * The action to display. It renders after the message, at the end of the snackbar.
   */
  action?: SnackbarContentProps['action'] | undefined;
  /**
   * The anchor of the `Snackbar`.
   * On smaller screens, the component grows to occupy all the available width,
   * the horizontal alignment is ignored.
   * @default { vertical: 'bottom', horizontal: 'left' }
   */
  anchorOrigin?: SnackbarOrigin | undefined;
  /**
   * The number of milliseconds to wait before automatically calling the
   * `onClose` function. `onClose` should then set the state of the `open`
   * prop to hide the Snackbar. This behavior is disabled by default with
   * the `null` value.
   * @default null
   */
  autoHideDuration?: number | null | undefined;
  /**
   * Replace the `SnackbarContent` component.
   */
  children?: React.ReactElement<unknown, any> | undefined;
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: Partial<SnackbarClasses> | undefined;
  /**
   * If `true`, the `autoHideDuration` timer will expire even if the window is not focused.
   * @default false
   */
  disableWindowBlurListener?: boolean | undefined;
  /**
   * When displaying multiple consecutive snackbars using a single parent-rendered
   * `<Snackbar/>`, add the `key` prop to ensure independent treatment of each message.
   * For instance, use `<Snackbar key={message} />`. Otherwise, messages might update
   * in place, and features like `autoHideDuration` could be affected.
   */
  key?: any;
  /**
   * The message to display.
   */
  message?: SnackbarContentProps['message'] | undefined;
  /**
   * Callback fired when the component requests to be closed.
   * Typically `onClose` is used to set state in the parent component,
   * which is used to control the `Snackbar` `open` prop.
   * The `reason` parameter can optionally be used to control the response to `onClose`,
   * for example ignoring `clickaway`.
   *
   * @param {React.SyntheticEvent<any> | Event} event The event source of the callback.
   * @param {string} reason Can be: `"timeout"` (`autoHideDuration` expired), `"clickaway"`, or `"escapeKeyDown"`.
   */
  onClose?:
    ((event: React.SyntheticEvent<any> | Event, reason: SnackbarCloseReason) => void) | undefined;
  /**
   * If `true`, the component is shown.
   */
  open?: boolean | undefined;
  /**
   * The number of milliseconds to wait before dismissing after user interaction.
   * If `autoHideDuration` prop isn't specified, it does nothing.
   * If `autoHideDuration` prop is specified but `resumeHideDuration` isn't,
   * we default to `autoHideDuration / 2` ms.
   */
  resumeHideDuration?: number | undefined;
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx?: SxProps<Theme> | undefined;
  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   * @default {
   *   enter: theme.transitions.duration.enteringScreen,
   *   exit: theme.transitions.duration.leavingScreen,
   * }
   */
  transitionDuration?: TransitionProps['timeout'] | undefined;
}

export default function Snackbar(props: SnackbarProps): React.JSX.Element;

export interface SnackbarOwnerState extends Omit<SnackbarProps, 'slots' | 'slotProps'> {}

vendor/src/SnackbarContent/SnackbarContent.d.ts

import * as React from 'react';

import { SxProps } from '@mui/system';

import { Theme } from '../styles';

import { InternalStandardProps as StandardProps } from '../internal';

import { PaperProps } from '../Paper';

import { SnackbarContentClasses } from './snackbarContentClasses';

export interface SnackbarContentProps extends StandardProps<PaperProps, 'children'> {
  /**
   * The action to display. It renders after the message, at the end of the snackbar.
   */
  action?: React.ReactNode;
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: Partial<SnackbarContentClasses> | undefined;
  /**
   * The message to display.
   */
  message?: React.ReactNode;
  /**
   * The ARIA role attribute of the element.
   * @default 'alert'
   */
  role?: PaperProps['role'] | undefined;
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx?: SxProps<Theme> | undefined;
}

export default function SnackbarContent(props: SnackbarContentProps): React.JSX.Element;

安装后验收

执行严格类型检查、生产构建和实际交互。检查键盘标签/焦点、原生支持的禁用/错误/只读语义、深浅色、窄屏和减少动画。按真实宿主数据检查回调,不把复制提示词当作安装完成。初始化工具还需检查服务端 HTML 与无告警水合。

来源与许可

https://github.com/mui/material-ui/tree/809a7717b4c050ba3f69b75300689f07c050a16e

MIT · @mui/material@9.4.0. 保留上游原始内容与许可证。上游完整原文保留于 vendor/docs,不标为全文中文化。