JGuang

穿梭列表

Transfer List · Material UI

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

穿梭列表

组合左右列表、选择状态和移动操作。

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

使用场景与业务边界

这是 Core 原语的组合,不存在单独 TransferList 导出;集合、移动规则和持久化由宿主负责。

原生组成与范围

List, ListItem, Checkbox, Switch

保持 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 结构、可空值与泛型仍按固定源码保留。

所属组件.属性用途说明声明来源
List.dense原生紧凑布局,仍须保留可读性与触控目标。List
Checkbox.checked受控二元选择,与原生变化回调配套。Checkbox
Checkbox.indeterminate汇总项部分选中的视觉状态,与 checked 分开。Checkbox

可运行原生示例

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

  • 基础穿梭列表 · TransferList · 上游原生示例
  • 增强穿梭列表 · SelectAllTransferList · 上游原生示例

真实使用示例

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

import * as React from 'react';
import Grid from '@mui/material/Grid';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import Checkbox from '@mui/material/Checkbox';
import Button from '@mui/material/Button';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import MenuItem from '@mui/material/MenuItem';
import MenuList from '@mui/material/MenuList';

function not(a: readonly number[], b: readonly number[]) {
  return a.filter((value) => !b.includes(value));
}

function intersection(a: readonly number[], b: readonly number[]) {
  return a.filter((value) => b.includes(value));
}

type CustomListProps = {
  items: readonly number[];
  checked: readonly number[];
  handleToggle: (value: number) => () => void;
};

const CustomList = React.forwardRef(function CustomList(
  props: CustomListProps,
  ref: React.Ref<HTMLDivElement & { focus: () => void }>,
) {
  const { items, checked, handleToggle } = props;

  return (
    <Paper sx={{ width: 200, height: 230, overflow: 'auto' }}>
      <MenuList dense component="div" role="list" ref={ref}>
        {items.map((value: number) => {
          const labelId = `transfer-list-item-${value}-label`;

          return (
            <MenuItem
              component="div"
              key={value}
              role="listitem"
              onClick={handleToggle(value)}
            >
              <ListItemIcon>
                <Checkbox
                  checked={checked.includes(value)}
                  tabIndex={-1}
                  disableRipple
                  slotProps={{
                    input: { 'aria-labelledby': labelId },
                  }}
                />
              </ListItemIcon>
              <ListItemText id={labelId} primary={`List item ${value + 1}`} />
            </MenuItem>
          );
        })}
      </MenuList>
    </Paper>
  );
});

export default function TransferList() {
  const [checked, setChecked] = React.useState<readonly number[]>([]);
  const [left, setLeft] = React.useState<readonly number[]>([0, 1, 2, 3]);
  const [right, setRight] = React.useState<readonly number[]>([4, 5, 6, 7]);

  const leftChecked = intersection(checked, left);
  const rightChecked = intersection(checked, right);

  const leftListRef = React.useRef<HTMLDivElement & { focus: () => void }>(null);
  const rightListRef = React.useRef<HTMLDivElement & { focus: () => void }>(null);

  const handleToggle = (value: number) => () => {
    const currentIndex = checked.indexOf(value);
    const newChecked = [...checked];

    if (currentIndex === -1) {
      newChecked.push(value);
    } else {
      newChecked.splice(currentIndex, 1);
    }

    setChecked(newChecked);
  };

  const handleAllRight = () => {
    setRight(right.concat(left));
    setLeft([]);
    setChecked(not(checked, left));
    rightListRef.current?.focus();
  };

  const handleCheckedRight = () => {
    setRight(right.concat(leftChecked));
    setLeft(not(left, leftChecked));
    setChecked(not(checked, leftChecked));
    rightListRef.current?.focus();
  };

  const handleCheckedLeft = () => {
    setLeft(left.concat(rightChecked));
    setRight(not(right, rightChecked));
    setChecked(not(checked, rightChecked));
    leftListRef.current?.focus();
  };

  const handleAllLeft = () => {
    setLeft(left.concat(right));
    setRight([]);
    setChecked(not(checked, right));
    leftListRef.current?.focus();
  };

  return (
    <Grid
      container
      spacing={2}
      sx={{ justifyContent: 'center', alignItems: 'center' }}
    >
      <CustomList
        ref={leftListRef}
        items={left}
        checked={checked}
        handleToggle={handleToggle}
      />
      <Stack>
        <Button
          sx={{ my: 0.5 }}
          variant="outlined"
          size="small"
          onClick={handleAllRight}
          disabled={left.length === 0}
          aria-label="move all right"
        >
          ≫
        </Button>
        <Button
          sx={{ my: 0.5 }}
          variant="outlined"
          size="small"
          onClick={handleCheckedRight}
          disabled={leftChecked.length === 0}
          aria-label="move selected right"
        >
          &gt;
        </Button>
        <Button
          sx={{ my: 0.5 }}
          variant="outlined"
          size="small"
          onClick={handleCheckedLeft}
          disabled={rightChecked.length === 0}
          aria-label="move selected left"
        >
          &lt;
        </Button>
        <Button
          sx={{ my: 0.5 }}
          variant="outlined"
          size="small"
          onClick={handleAllLeft}
          disabled={right.length === 0}
          aria-label="move all left"
        >
          ≪
        </Button>
      </Stack>
      <CustomList
        ref={rightListRef}
        items={right}
        checked={checked}
        handleToggle={handleToggle}
      />
    </Grid>
  );
}

示例依赖边界

react, @mui/material/Grid, @mui/material/ListItemIcon, @mui/material/ListItemText, @mui/material/Checkbox, @mui/material/Button, @mui/material/Paper, @mui/material/Stack, @mui/material/MenuItem, @mui/material/MenuList, @mui/material/Card, @mui/material/CardHeader, @mui/material/Divider

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

固定上游 API 元数据参考

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

List

import List from '@mui/material/List';
import { List } from '@mui/material';
属性必需上游元数据类型/约束元数据默认值
children否node—
classes否object—
component否elementType—
dense否boolfalse
disablePadding否boolfalse
subheader否node—
sx否Array<func | object | bool> | func | object—

ListItem

import ListItem from '@mui/material/ListItem';
import { ListItem } from '@mui/material';
属性必需上游元数据类型/约束元数据默认值
alignItems否'center' | 'flex-start''center'
children否node—
classes否object—
component否elementType—
dense否boolfalse
disableGutters否boolfalse
disablePadding否boolfalse
divider否boolfalse
secondaryAction否node—
slotProps否{ root?: func | object, secondaryAction?: func | object }{}
slots否{ root?: elementType, secondaryAction?: elementType }{}
sx否Array<func | object | bool> | func | object—

Checkbox

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

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

属性必需上游元数据类型/约束元数据默认值
checked否bool—
checkedIcon否node<CheckBoxIcon />
classes否object—
color否'default' | 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning' | string'primary'
defaultChecked否bool—
disabled否boolfalse
disableRipple否boolfalse
icon否node<CheckBoxOutlineBlankIcon />
id否string—
indeterminate否boolfalse
indeterminateIcon否node<IndeterminateCheckBoxIcon />
onChange否func—
required否boolfalse
size否'medium' | 'small' | string'medium'
slotProps否{ input?: func | object, root?: func | object }{}
slots否{ input?: elementType, root?: elementType }{}
sx否Array<func | object | bool> | func | object—
value否any—

Switch

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

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

属性必需上游元数据类型/约束元数据默认值
checked否bool—
checkedIcon否node—
classes否object—
color否'default' | 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning' | string'primary'
defaultChecked否bool—
disabled否bool—
disableRipple否boolfalse
edge否'end' | 'start' | falsefalse
icon否node—
id否string—
onChange否func—
required否boolfalse
size否'medium' | 'small' | string'medium'
slotProps否{ input?: func | object, root?: func | object, switchBase?: func | object, thumb?: func | object, track?: func | object }{}
slots否{ input?: elementType, root?: elementType, switchBase?: elementType, thumb?: elementType, track?: elementType }{}
sx否Array<func | object | bool> | func | object—
value否any—

原生源码声明

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

vendor/src/List/List.d.ts

import * as React from 'react';

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

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

import { OverridableComponent, OverridableTypeMap, OverrideProps } from '../OverridableComponent';

import { ListClasses } from './listClasses';

export interface ListOwnProps {
  /**
   * The content of the component.
   */
  children?: React.ReactNode;
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: Partial<ListClasses> | undefined;
  /**
   * If `true`, compact vertical padding designed for keyboard and mouse input is used for
   * the list and list items.
   * The prop is available to descendant components as the `dense` context.
   * @default false
   */
  dense?: boolean | undefined;
  /**
   * If `true`, vertical padding is removed from the list.
   * @default false
   */
  disablePadding?: boolean | undefined;
  /**
   * The content of the subheader, normally `ListSubheader`.
   */
  subheader?: React.ReactNode;
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx?: SxProps<Theme> | undefined;
}

export interface ListTypeMap<AdditionalProps = {}, RootComponent extends React.ElementType = 'ul'> {
  props: AdditionalProps & ListOwnProps;
  defaultComponent: RootComponent;
}

export interface ExtendListTypeMap<TypeMap extends OverridableTypeMap> {
  props: TypeMap['props'] & Omit<ListTypeMap['props'], keyof TypeMap['props']>;
  defaultComponent: TypeMap['defaultComponent'];
}

export type ExtendList<TypeMap extends OverridableTypeMap> = OverridableComponent<
  ExtendListTypeMap<TypeMap>
>;

declare const List: ExtendList<ListTypeMap>;

export type ListProps<
  RootComponent extends React.ElementType = ListTypeMap['defaultComponent'],
  AdditionalProps = {},
> = OverrideProps<ListTypeMap<AdditionalProps, RootComponent>, RootComponent> & {
  component?: React.ElementType | undefined;
};

vendor/src/ListItem/ListItem.d.ts

import * as React from 'react';

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

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

import { OverridableComponent, OverrideProps } from '../OverridableComponent';

import { ListItemClasses } from './listItemClasses';

import { SlotProps } from '../utils/types';

export interface ListItemRootSlotPropsOverrides {}

export interface ListItemSecondaryActionSlotPropsOverrides {}

export interface ListItemBaseProps {
  /**
   * Defines the `align-items` style property.
   * @default 'center'
   */
  alignItems?: 'flex-start' | 'center' | undefined;
  /**
   * The content of the component.
   */
  children?: React.ReactNode;
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: Partial<ListItemClasses> | undefined;
  /**
   * If `true`, compact vertical padding designed for keyboard and mouse input is used.
   * The prop defaults to the value inherited from the parent List component.
   * @default false
   */
  dense?: boolean | undefined;
  /**
   * If `true`, the left and right padding is removed.
   * @default false
   */
  disableGutters?: boolean | undefined;
  /**
   * If `true`, all padding is removed.
   * @default false
   */
  disablePadding?: boolean | undefined;
  /**
   * If `true`, a 1px light border is added to the bottom of the list item.
   * @default false
   */
  divider?: boolean | undefined;
  /**
   * The element to display at the end of ListItem.
   */
  secondaryAction?: React.ReactNode;
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx?: SxProps<Theme> | undefined;
}

export interface ListItemOwnerState extends Omit<ListItemProps, 'slots' | 'slotProps'> {}

export interface ListItemOwnProps extends ListItemBaseProps {
  /**
   * The extra props for the slot components.
   * You can override the existing props or add new ones.
   *
   * @default {}
   */
  slotProps?:
    | {
        root?:
          | SlotProps<
              React.ElementType<React.HTMLAttributes<HTMLDivElement>>,
              ListItemRootSlotPropsOverrides,
              ListItemOwnerState
            >
          | undefined;
        secondaryAction?:
          | SlotProps<
              React.ElementType<React.HTMLAttributes<HTMLDivElement>>,
              ListItemSecondaryActionSlotPropsOverrides,
              ListItemOwnerState
            >
          | undefined;
      }
    | undefined;
  /**
   * The components used for each slot inside.
   *
   * @default {}
   */
  slots?:
    | {
        root?: React.ElementType | undefined;
        secondaryAction?: React.ElementType | undefined;
      }
    | undefined;
}

export interface ListItemTypeMap<AdditionalProps, RootComponent extends React.ElementType> {
  props: AdditionalProps & ListItemOwnProps;
  defaultComponent: RootComponent;
}

declare const ListItem: OverridableComponent<ListItemTypeMap<{}, 'li'>>;

export type ListItemProps<
  RootComponent extends React.ElementType = 'li',
  AdditionalProps = {},
> = OverrideProps<ListItemTypeMap<AdditionalProps, RootComponent>, RootComponent> & {
  component?: React.ElementType | undefined;
};

vendor/src/Checkbox/Checkbox.d.ts

import * as React from 'react';

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

import { OverridableStringUnion } from '@mui/types';

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

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

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

import { SwitchBaseProps } from '../internal/SwitchBase';

import { CheckboxClasses } from './checkboxClasses';

export interface CheckboxPropsSizeOverrides {}

export interface CheckboxPropsColorOverrides {}

export interface CheckboxRootSlotPropsOverrides {}

export interface CheckboxInputSlotPropsOverrides {}

export interface CheckboxSlots {
  /**
   * The component that renders the root slot.
   * @default SwitchBase
   */
  root: React.ElementType;
  /**
   * The component that renders the input slot.
   * @default SwitchBase's input
   */
  input: React.ElementType;
}

export type CheckboxSlotsAndSlotProps = CreateSlotsAndSlotProps<
  CheckboxSlots,
  {
    /**
     * Props forwarded to the root slot.
     * By default, the available props are based on the div element.
     */
    root: SlotProps<
      React.ElementType<SwitchBaseProps>,
      CheckboxRootSlotPropsOverrides,
      CheckboxOwnerState
    >;
    /**
     * Props forwarded to the input slot.
     * By default, the available props are based on the input element.
     */
    input: SlotProps<'input', CheckboxInputSlotPropsOverrides, CheckboxOwnerState>;
  }
>;

export interface CheckboxProps
  extends
    StandardProps<
      SwitchBaseProps,
      'checkedIcon' | 'color' | 'icon' | 'type' | 'slots' | 'slotProps'
    >,
    CheckboxSlotsAndSlotProps {
  /**
   * If `true`, the component is checked.
   */
  checked?: SwitchBaseProps['checked'] | undefined;
  /**
   * The icon to display when the component is checked.
   * @default <CheckBoxIcon />
   */
  checkedIcon?: React.ReactNode;
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: Partial<CheckboxClasses> | undefined;
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).
   * @default 'primary'
   */
  color?:
    | OverridableStringUnion<
        'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning' | 'default',
        CheckboxPropsColorOverrides
      >
    | undefined;
  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled?: SwitchBaseProps['disabled'] | undefined;
  /**
   * If `true`, the ripple effect is disabled.
   * @default false
   */
  disableRipple?: SwitchBaseProps['disableRipple'] | undefined;
  /**
   * The icon to display when the component is unchecked.
   * @default <CheckBoxOutlineBlankIcon />
   */
  icon?: React.ReactNode;
  /**
   * The id of the `input` element.
   */
  id?: SwitchBaseProps['id'] | undefined;
  /**
   * If `true`, the component appears indeterminate.
   * This does not set the native input element to indeterminate due
   * to inconsistent behavior across browsers.
   * However, we set a `data-indeterminate` attribute on the `input`.
   * @default false
   */
  indeterminate?: boolean | undefined;
  /**
   * The icon to display when the component is indeterminate.
   * @default <IndeterminateCheckBoxIcon />
   */
  indeterminateIcon?: React.ReactNode;
  /**
   * Callback fired when the state is changed.
   *
   * @param {React.ChangeEvent<HTMLInputElement>} event The event source of the callback.
   * You can pull out the new checked state by accessing `event.target.checked` (boolean).
   */
  onChange?: SwitchBaseProps['onChange'] | undefined;
  /**
   * If `true`, the `input` element is required.
   * @default false
   */
  required?: SwitchBaseProps['required'] | undefined;
  /**
   * The size of the component.
   * `small` is equivalent to the dense checkbox styling.
   * @default 'medium'
   */
  size?:
    OverridableStringUnion<'small' | 'medium' | 'large', CheckboxPropsSizeOverrides> | undefined;
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx?: SxProps<Theme> | undefined;
  /**
   * The value of the component. The DOM API casts this to a string.
   * The browser uses "on" as the default value.
   */
  value?: SwitchBaseProps['value'] | undefined;
}

export interface CheckboxOwnerState extends Omit<CheckboxProps, 'slots' | 'slotProps'> {}

export default function Checkbox(props: CheckboxProps): React.JSX.Element;

vendor/src/Switch/Switch.d.ts

import * as React from 'react';

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

import { OverridableStringUnion } from '@mui/types';

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

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

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

import { SwitchBaseProps } from '../internal/SwitchBase';

import { SwitchClasses } from './switchClasses';

export interface SwitchPropsSizeOverrides {}

export interface SwitchPropsColorOverrides {}

export interface SwitchRootSlotPropsOverrides {}

export interface SwitchTrackSlotPropsOverrides {}

export interface SwitchThumbSlotPropsOverrides {}

export interface SwitchSwitchBaseSlotPropsOverrides {}

export interface SwitchInputSlotPropsOverrides {}

export interface SwitchSlots {
  /**
   * The component that renders the root slot.
   * @default 'span'
   */
  root: React.ElementType;
  /**
   * The component that renders the track slot.
   * @default 'span'
   */
  track: React.ElementType;
  /**
   * The component that renders the thumb slot.
   * @default 'span'
   */
  thumb: React.ElementType;
  /**
   * The component that renders the switchBase slot.
   * @default SwitchBase
   */
  switchBase: React.ElementType;
  /**
   * The component that renders the switchBase's input slot.
   * @default SwitchBaseInput
   */
  input: React.ElementType;
}

export type SwitchSlotsAndSlotProps = CreateSlotsAndSlotProps<
  SwitchSlots,
  {
    /**
     * Props forwarded to the root slot.
     * By default, the available props are based on the span element.
     */
    root: SlotProps<'span', SwitchRootSlotPropsOverrides, SwitchOwnerState>;
    /**
     * Props forwarded to the track slot.
     * By default, the available props are based on the span element.
     */
    track: SlotProps<'span', SwitchTrackSlotPropsOverrides, SwitchOwnerState>;
    /**
     * Props forwarded to the thumb slot.
     * By default, the available props are based on the span element.
     */
    thumb: SlotProps<'span', SwitchThumbSlotPropsOverrides, SwitchOwnerState>;
    /**
     * Props forwarded to the switchBase slot.
     * By default, the available props are based on the internal SwitchBase component.
     */
    switchBase: SlotProps<
      React.ElementType<SwitchBaseProps>,
      SwitchSwitchBaseSlotPropsOverrides,
      SwitchOwnerState
    >;
    /**
     * Props forwarded to the input slot.
     * By default, the available props are based on the input element.
     */
    input: SlotProps<'input', SwitchInputSlotPropsOverrides, SwitchOwnerState>;
  }
>;

export interface SwitchOwnerState extends Omit<SwitchProps, 'slots' | 'slotProps'> {}

export interface SwitchProps
  extends
    StandardProps<SwitchBaseProps, 'checkedIcon' | 'color' | 'icon' | 'slots' | 'slotProps'>,
    SwitchSlotsAndSlotProps {
  /**
   * The icon to display when the component is checked.
   */
  checkedIcon?: React.ReactNode;
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: Partial<SwitchClasses> | undefined;
  /**
   * The color of the component.
   * It supports both default and custom theme colors, which can be added as shown in the
   * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).
   * @default 'primary'
   */
  color?:
    | OverridableStringUnion<
        'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning' | 'default',
        SwitchPropsColorOverrides
      >
    | undefined;
  /**
   * If `true`, the component is disabled.
   */
  disabled?: boolean | undefined;
  /**
   * The icon to display when the component is unchecked.
   */
  icon?: React.ReactNode;
  /**
   * The size of the component.
   * `small` is equivalent to the dense switch styling.
   * @default 'medium'
   */
  size?: OverridableStringUnion<'small' | 'medium', SwitchPropsSizeOverrides> | undefined;
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx?: SxProps<Theme> | undefined;
  /**
   * The value of the component. The DOM API casts this to a string.
   * The browser uses "on" as the default value.
   */
  value?: unknown;
}

export default function Switch(props: SwitchProps): React.JSX.Element;

安装后验收

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

来源与许可

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

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