Перейти к основному содержанию

Обзор

Slider поддерживает одно число или массив чисел для диапазона. Скомпонуйте его метку, трек, индикатор и бегунки внутри Root.

Использование

Неконтролируемое состояние

Используйте defaultValue, чтобы задать начальную громкость. Ползунок управляет последующими изменениями.

Варианты оформления

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

Анатомия интерфейса.

Поместите дорожку и бегунки внутрь Slider.Control, который обрабатывает взаимодействие с указателем. Это дерево показывает слайдер с одним бегунком.
Для диапазона добавьте бегунок для каждого значения с соответствующим index и уникальным доступным именем. Метки и числовой вывод остаются за пределами Control, поэтому они не становятся частью перетаскиваемой области.

Контролируемое состояние

Передайте value и обновляйте его с помощью onValueChange, чтобы управлять той же громкостью в состоянии React. Функция обратного вызова получает следующее значение и сведения о событии.
Используйте onValueChange, чтобы поддерживать актуальность контролируемого значения во время взаимодействия. onValueCommitted обрабатывает окончательное значение после завершения взаимодействия, например для его сохранения. Обе функции обратного вызова также доступны в неконтролируемом режиме без управления значением. Сведения об изменении включают исходное event, reason взаимодействия, activeThumbIndex и cancel(). Сведения о фиксации используют общий контракт событий Base UI и не включают отмену изменения. Отмененное изменение не фиксируется.

Диапазон

Задайте бегункам диапазона разные доступные имена и index, соответствующий их значению. minStepsBetweenValues задает минимальный промежуток в шагах. Универсальный тип значения корневого элемента — число или доступный только для чтения массив чисел. Чтобы управлять диапазоном, сохраните массив в состоянии React и передайте его через value и onValueChange, как и для одного значения.

Клавиатура и внешний вид

Клавиши со стрелками изменяют сфокусированный бегунок на один шаг. Home и End перемещают его к границам с учетом ограничений диапазона. orientation="vertical" изменяет компоновку и направление управления с клавиатуры. Используйте disabled в Root, чтобы предотвратить изменения. Укажите color="success" для альтернативной палитры; по умолчанию используется accent. Значение thumbAlignment по умолчанию — edge. Передайте center или edge-client-only, чтобы переопределить его. Нативная композиция className, style и render остается доступной для каждой части, включая функции состояния.
При выравнивании edge и edge-client-only Base UI 1.8 и 1.9 никогда не выполняют повторное измерение бегунка после изменения размера его Slider.Control, а ползунок, смонтированный в скрытом состоянии, сохраняет свои бегунки скрытыми после отображения (mui/base-ui#5995). Компоненты интерфейса React сталкиваются с той же проблемой при первом рендеринге. Используйте thumbAlignment="center", пока исправление не войдет в релиз Base UI (mui/base-ui#6000).

Нативная интеграция и типы

Slider.Root выводит число или доступный только для чтения числовой массив из value или defaultValue, сохраняя этот тип в обоих обратных вызовах. SliderRootProps по умолчанию принимает оба варианта; используйте SliderRootProps\<number> для помощников с одним значением или SliderRootProps\<readonly number[]> для помощников диапазона. Каждая часть имеет экспортируемый тип свойств в twenty-ui/primitives/input: SliderRootProps, SliderControlProps, SliderTrackProps, SliderIndicatorProps, SliderThumbProps, SliderLabelProps и SliderValueProps. Refs указывают на элементы div для Root, Control, Track, Indicator, Thumb и Label, а для Value — на элемент output. Ref Thumb указывает на его видимый ползунок; его доступное имя и нативное значение формы принадлежат вложенному диапазонному input. Используйте name и form в Root для нативной отправки, с одним input для каждого значения диапазона.

Свойства

Справочник формируется на основе публичных типов компонентов. Собственные атрибуты, включая доступные имена и обработчики событий, также принимаются частями, которые отображают элементы.

Slider.Root

string | ((state: SliderRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
"accent" | "success"
по умолчанию:"accent"
Color of the indicator and thumbs.
number | readonly number[]
The uncontrolled value of the slider when it’s initially rendered.To render a controlled slider, use the value prop instead.
boolean
по умолчанию:"false"
Whether the slider should ignore user interaction.
string
Identifies the form that owns the slider inputs. Useful when the slider is rendered outside the form.
NumberFormatOptions
Options to format the value.
number
по умолчанию:"10"
The granularity with which the slider can step through values when using Page Up/Page Down or Shift + Arrow Up/Arrow Down.
LocalesArgument
The locale used by Intl.NumberFormat when formatting the value. Defaults to the user’s runtime locale.
number
по умолчанию:"100"
The maximum allowed value of the slider. Should not be equal to min.
number
по умолчанию:"0"
The minimum allowed value of the slider. Should not be equal to max.
number
по умолчанию:"0"
The minimum steps between values in a range slider.
string
Identifies the field when a form is submitted.
((value: TValue extends number ? number : TValue, eventDetails: SliderRootChangeEventDetails) => void)
Callback function that is fired when the slider’s value changed. Receives the new value as the first argument; the originating event is available as eventDetails.event. The value is also reflected on eventDetails.event.target.value for form integration.The eventDetails.reason indicates what triggered the change:
  • 'input-change' when the hidden range input emits a change event (for example, via form integration)
  • 'track-press' when the control track is pressed
  • 'drag' while dragging a thumb
  • 'keyboard' for keyboard input
  • 'none' when the change is triggered without a specific interaction
((value: TValue extends number ? number : TValue, eventDetails: SliderRootCommitEventDetails) => void)
Callback function that is fired when a value change is committed. Does not fire if the value did not change, or if the change was canceled. Warning: This is a generic event, not a change event.The eventDetails.reason indicates what triggered the commit:
  • 'drag' while dragging a thumb
  • 'track-press' when the control track is pressed
  • 'keyboard' for keyboard input
  • 'input-change' when the hidden range input emits a change event (for example, via form integration)
  • 'none' when the commit occurs without a specific interaction
"horizontal" | "vertical"
по умолчанию:"horizontal"
The component orientation.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SliderRootState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
number
по умолчанию:"1"
The granularity with which the slider can step through values. (A “discrete” slider.) The min prop serves as the origin for the valid values. We recommend (max - min) to be evenly divisible by the step.
CSSProperties | ((state: SliderRootState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
"center" | "edge-client-only" | "edge"
по умолчанию:"edge"
How the thumb(s) are aligned relative to Slider.Control when the value is at min or max:
  • center: The center of the thumb is aligned with the control edge
  • edge: The thumb is inset within the control such that its edge is aligned with the control edge
  • edge-client-only: Same as edge but renders after React hydration on the client, reducing bundle size in return
"none" | "push" | "swap"
по умолчанию:"push"
Controls how thumbs behave when they collide during pointer interactions.
  • 'push' (default): Thumbs push each other without restoring their previous positions when dragged back.
  • 'swap': Thumbs swap places when dragged past each other.
  • 'none': Thumbs cannot move past each other; excess movement is ignored.
number | readonly number[]
The value of the slider. For range sliders, provide an array with one value per thumb.

Slider.Control

string | ((state: SliderControlState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SliderControlState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SliderControlState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Slider.Track

string | ((state: SliderTrackState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SliderTrackState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SliderTrackState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Slider.Indicator

string | ((state: SliderIndicatorState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SliderIndicatorState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SliderIndicatorState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Slider.Thumb

string
A string value forwarded to the aria-valuetext attribute of the input. Ignored when getAriaValueText is provided.
string | ((state: SliderThumbState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
по умолчанию:"false"
Whether the thumb should ignore user interaction.
((index: number) => string) | null
A function which returns a string value for the aria-label attribute of the input.
((formattedValue: string, value: number, index: number) => string) | null
A function which returns a string value for the aria-valuetext attribute of the input. This is important for screen reader users.
number
The index of the thumb which corresponds to the index of its value in the value or defaultValue array. This prop is required to support server-side rendering for range sliders with multiple thumbs.
Ref<HTMLInputElement>
A ref to access the nested input element.
FocusEventHandler<HTMLInputElement>
A blur handler forwarded to the input.
FocusEventHandler<HTMLInputElement>
A focus handler forwarded to the input.
KeyboardEventHandler<HTMLInputElement>
A keydown handler forwarded to the input.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SliderThumbState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SliderThumbState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
number
Optional tab index attribute forwarded to the input.

Slider.Label

string | ((state: SliderRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SliderRootState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SliderRootState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Slider.Value

string | ((state: SliderValueState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SliderValueState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: SliderValueState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.