JGuang

开关

Switch · Mantine Core

交互预览
npm install @mantine/core@9.7.1 @mantine/hooks@9.7.1

开关

Mantine Core 的独立组件,请不要替换为 JGuang UI/Base UI 的同名 API。

安装

npm install @mantine/core@9.7.1 @mantine/hooks@9.7.1

入口引入 @mantine/core/styles.css,并在根组件使用 MantineProvider;通过 forceColorScheme 同步深浅色主题。

使用与验证

在左侧选择组件,在预览中操作它的状态;使用“查看代码”检查真实源码。安装后执行类型检查和构建,再验证键盘焦点、手机布局与深浅色主题。

来源

https://github.com/mantinedev/mantine/tree/f0e2bc6d28b0f0b8aaefb5b859937bf77f539df7 MIT 许可证;不包括付费内容。下方提供上游英文参考内容,中文使用指南已适配;上游详细参考暂保留英文。


版本与兼容性

固定的 Mantine Core 9.7.1 要求 React 和 React DOM 满足 ^19.2.0,并配套 @mantine/hooks@9.7.1。此条件来自实际 npm 包的 peerDependencies。React 18 或其他不兼容版本不能强行安装;先向项目负责人说明升级影响并确认方案,不使用 --force/--legacy-peer-deps 掩盖冲突。入口的原生 Provider 开启 theme.respectReducedMotion,并用 forceColorScheme 控制深浅色。

适用场景

切换布尔设置。

本地示例使用的原生参数

以下参数由本地、经过类型检查的 JSX 示例提取,按所属组件区分。不是全部属性清单;完整签名和继承关系见下方固定源码参考。

组件参数说明
Switch.disabled禁用用户输入或操作,不等同于只读。
Switch.label可见标签或当前组件的标签内容。

交互与状态检查

当前场景:默认、禁用。切换支持的禁用、错误或只读场景后检查真实行为;无此原生状态的组件不会被强行添加统一属性。验证键盘焦点和退出方式,修改值后按原生回调签名连接业务状态。

业务接入边界

示例内容和状态仅保存在本地,不提供服务端持久化、授权或数据请求。静态展示组件不应被当作已完成的业务流程。

宿主配置

先安装固定版本 @mantine/core 和 @mantine/hooks,在入口引入 @mantine/core/styles.css,并使用 MantineProvider。示例的 theme 和 variant 是 JGuang 编写的宿主参数,不是所有原生组件都接受的统一 API;通过 forceColorScheme 同步应用主题。源码面板中的原生实现仅供阅读,使用 npm 导出,不要单独复制内部实现。此批只覆盖 Core,不包括日期、图表和表单扩展包。上游详细说明保留英文,不宣称全文中文化。

可运行用法

以下代码使用资源原生 API;不是把其他设计系统的同名组件替换进来。

import { useState } from 'react';
import * as M from '@mantine/core';
import '@mantine/core/styles.css';


function ComponentPreview({ variant = 'Default' }: { variant?: string }) {
const disabled = variant === "Disabled";
return <M.Switch disabled={disabled} label="Dark mode / 深色模式" />;
}
export default function Example({ variant = 'Default', theme = 'light' }: { variant?: string; theme?: 'light' | 'dark' }) {
return <M.MantineProvider forceColorScheme={theme} theme={{ respectReducedMotion: true }}><ComponentPreview variant={variant} /></M.MantineProvider>;
}

可用状态与示例

默认、禁用

示例遵循 Mantine 原生 API。支持多状态的输入组件可将示例中的 variant 改为 Disabled、Invalid 或 Read only;这些只是示例标签,不是新增的组件属性。改造时保留组件要求的数据、受控值、store 和复合子组件结构。

Usage

Controlled

import { useState } from 'react';
import { Switch } from '@mantine/core';

function Demo() {
  const [checked, setChecked] = useState(false);
  return (
    <Switch
      checked={checked}
      onChange={(event) => setChecked(event.currentTarget.checked)}
    />
  );
}

Uncontrolled

Switch can be used with uncontrolled forms the same way as a native input[type="checkbox"]. Set the name attribute to include switch value in FormData object on form submission. To control the initial checked state in uncontrolled forms, use defaultChecked prop.

Example usage of uncontrolled Switch with FormData:

import { Switch } from '@mantine/core';

function Demo() {
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        const formData = new FormData(event.currentTarget);
        console.log('Switch value:', !!formData.get('notifications'));
      }}
    >
      <Switch label="Enable notifications" name="notifications" defaultChecked />
      <button type="submit">Submit</button>
    </form>
  );
}

States

Inner Labels

Icon labels

Thumb icon

With tooltip

Set refProp="rootRef" on Tooltip and other similar components to make them work with Switch:

Pointer cursor

By default, the switch input and label have cursor: default (same as native input[type="checkbox"]). To change the cursor to pointer, set cursorType on the theme:

import { createTheme, MantineProvider, Switch } from '@mantine/core';

const theme = createTheme({
  cursorType: 'pointer',
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      <Switch label="Pointer cursor" />
    </MantineProvider>
  );
}

Switch.Group

Switch.Group with uncontrolled forms

Switch.Group can be used with uncontrolled forms, it renders a hidden input which joins all checked values into a single string using hiddenInputValuesSeparator prop.

Props for usage with uncontrolled forms:

  • name – name attribute passed to the hidden input
  • hiddenInputValuesSeparator – string used to join checked values into a single string, ',' by default
  • hiddenInputProps – additional props passed to the hidden input
export function UncontrolledForm() {
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        const formData = new FormData(event.currentTarget);
        console.log('Switch group value:', formData.get('frameworks'));
      }}
    >
      <Switch.Group label="Frameworks" name="frameworks" hiddenInputValuesSeparator="|">
        <Switch label="React" value="react" />
        <Switch label="Angular" value="ng" />
      </Switch.Group>
      <button type="submit">Submit</button>
    </form>
  );
}

maxSelectedValues

Use maxSelectedValues prop to limit the number of selected values in Switch.Group. When the limit is reached, the remaining switches are disabled and cannot be selected.

Switch.Group disabled

Controlled Switch.Group

import { useState } from 'react';
import { Switch } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState<string[]>([]);

  return (
    <Switch.Group value={value} onChange={setValue}>
      <Switch value="react" label="React" />
      <Switch value="svelte" label="Svelte" />
    </Switch.Group>
  );
}

Change styles based on checked state

Get input ref

import { useRef } from 'react';
import { Switch } from '@mantine/core';

function Demo() {
  const ref = useRef<HTMLInputElement>(null);
  return <Switch ref={ref} />;
}

Accessibility

Switch is a regular input[type="checkbox"]. Set aria-label if the Switch is used without the label prop:

import { Switch } from '@mantine/core';

// -> not ok, input is not labeled
function Bad() {
  return <Switch />;
}

// -> ok, input has aria-label
function Good() {
  return <Switch aria-label="I agree to everything" />;
}

// -> ok, input has associated label
function AlsoGood() {
  return <Switch label="I agree to everything" />;
}

源码参数参考

以下实现签名和类型从本地固定版本源码生成。保留可选属性、原生继承类型、联合分支和 never 限制;不会将其他设计系统的 API 混入。forwardRef 实现中的 ref 属于 React 引用,不是新增业务属性。此区域是原始类型参考,不是上游说明的全文翻译。

Switch(_props)
export type SwitchStylesNames =
  | 'root'
  | 'track'
  | 'trackLabel'
  | 'thumb'
  | 'input'
  | InlineInputStylesNames;

export type SwitchCssVariables = {
  root:
    | '--switch-radius'
    | '--switch-height'
    | '--switch-width'
    | '--switch-thumb-size'
    | '--switch-label-font-size'
    | '--switch-track-label-padding'
    | '--switch-color';
};

export interface SwitchProps
  extends BoxProps, StylesApiProps<SwitchFactory>, ElementProps<'input', 'size' | 'children'> {
  /** Id used to bind input and label, if not passed, unique id will be generated instead */
  id?: string;

  /** Content of the label associated with the switch */
  label?: React.ReactNode;

  /** Inner label when the `Switch` is in unchecked state */
  offLabel?: React.ReactNode;

  /** Inner label when the `Switch` is in checked state */
  onLabel?: React.ReactNode;

  /** Key of `theme.colors` or any valid CSS color to set input color in checked state @default theme.primaryColor */
  color?: MantineColor;

  /** Controls size of all elements */
  size?: MantineSize | (string & {});

  /** Key of `theme.radius` or any valid CSS value to set `border-radius` @default 'xl' */
  radius?: MantineRadius;

  /** Props passed down to the root element */
  wrapperProps?: React.ComponentProps<'div'> & DataAttributes;

  /** Icon inside the thumb of the switch */
  thumbIcon?: React.ReactNode;

  /** Position of the label relative to the input @default 'right' */
  labelPosition?: 'left' | 'right';

  /** Description displayed below the label */
  description?: React.ReactNode;

  /** Error displayed below the label */
  error?: React.ReactNode;

  /** Assigns ref of the root element */
  rootRef?: React.Ref<HTMLDivElement>;

  /** If set, displays a colored dot inside the thumb that matches the track background color @default true */
  withThumbIndicator?: boolean;
}

export type SwitchFactory = Factory<{
  props: SwitchProps;
  ref: HTMLInputElement;
  stylesNames: SwitchStylesNames;
  vars: SwitchCssVariables;
  staticComponents: {
    Group: typeof SwitchGroup;
  };
}>;

export type Mod = Record<string, any> | string;

export type BoxMod = Mod | Mod[] | BoxMod[];

export interface BoxProps extends MantineStyleProps {
  /** Class added to the root element, if applicable */
  className?: string | undefined;

  /** Inline style added to root component element, can subscribe to theme defined on MantineProvider */
  style?: MantineStyleProp;

  /** CSS variables defined on root component element */
  __vars?: CssVarsProp;

  /** `size` property passed down the HTML element */
  __size?: string;

  /** Breakpoint above which the component is hidden with `display: none` */
  hiddenFrom?: MantineBreakpoint;

  /** Breakpoint below which the component is hidden with `display: none` */
  visibleFrom?: MantineBreakpoint;

  /** Determines whether component should be hidden in light color scheme with `display: none` */
  lightHidden?: boolean;

  /** Determines whether component should be hidden in dark color scheme with `display: none` */
  darkHidden?: boolean;

  /** Element modifiers transformed into `data-` attributes, for example, `{ 'data-size': 'xl' }`, falsy values are removed */
  mod?: BoxMod;
}

export type ElementProps<
  ElementType extends React.ElementType,
  PropsToOmit extends string = never,
> = Omit<React.ComponentProps<ElementType>, 'style' | PropsToOmit>;

export interface CSSProperties extends React.CSSProperties {
  [key: string]: any;
}

type MantineStyle = CSSProperties | ((theme: MantineTheme) => CSSProperties);

export type MantineStyleProp = MantineStyle | MantineStyle[] | MantineStyleProp[] | undefined;

export type CssVariable = `--${string}`;

export type CssVariables<Variable extends string = CssVariable> = Partial<Record<Variable, string>>;

export type CssVars<Variable extends string = CssVariable> =
  | CssVariables<Variable>
  | ((theme: MantineTheme) => CssVariables<Variable>)
  | CssVars<Variable>[];

export type CssVarsProp<Variable extends string = CssVariable> =
  | CssVars<Variable>
  | CssVars<Variable>[];

原生与外部类型

以下外部类型仍由 React 或资源自身依赖定义,没有手工展开为虚构属性。实际可用类型以安装版本的 TypeScript 检查为准。

Factory<{
  props: SwitchProps;
  ref: HTMLInputElement;
  stylesNames: SwitchStylesNames;
  vars: SwitchCssVariables;
  staticComponents: {
    Group: typeof SwitchGroup;
  };
}>
MantineStyleProps
React.CSSProperties
MantineTheme
Partial<Record<Variable, string>>
Record<Variable, string>
Variable
MantineBreakpoint
Record<string, any>
StylesApiProps<SwitchFactory>
React.ElementType
Omit<React.ComponentProps<ElementType>, 'style' | PropsToOmit>
React.ComponentProps<ElementType>
ElementType
PropsToOmit
React.ReactNode
MantineColor
MantineSize
MantineRadius
React.ComponentProps<'div'>
DataAttributes
React.Ref<HTMLDivElement>
HTMLDivElement
HTMLInputElement
InlineInputStylesNames