> ## Documentation Index
> Fetch the complete documentation index at: https://docs.twenty.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Строка настроек

> Строка переключателя с меткой, плоскими свойствами элемента управления и нативной композицией метки.

## Обзор

`SettingsRow` сочетает внешний вид [ListItem](https://docs.twenty.com/ru/ui/primitives/navigation/list-item.md) с [Switch](https://docs.twenty.com/ru/ui/primitives/input/switch.md). Он отображает нативную метку, связанную с его переключателем. Ваше приложение предоставляет содержимое строки и управляет любыми обновлениями настроек.

**Light**

[Пример строки настроек (light)](https://storybook.twenty.com/iframe.html?id=ui-components-settingsrow--display\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Пример строки настроек (dark)](https://storybook.twenty.com/iframe.html?id=ui-components-settingsrow--display\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-components-settingsrow--display)

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

```tsx theme={null}
import { SettingsRow } from 'twenty-ui/components/settings';
import { IconBell } from 'twenty-ui/icon';

export const NotificationSetting = () => (
  <SettingsRow startElement={<IconBell aria-hidden />}>
    Notifications
  </SettingsRow>
);
```

## Визуальные параметры

Сравните размеры переключателей и состояния «включено», «отключено» и «только для чтения».

**Light**

[Размеры и состояния строки настроек (light)](https://storybook.twenty.com/iframe.html?id=ui-components-settingsrow--catalog\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Размеры и состояния строки настроек (dark)](https://storybook.twenty.com/iframe.html?id=ui-components-settingsrow--catalog\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-components-settingsrow--catalog)

## Настройте переключатель

Передавайте [пропсы Switch](https://docs.twenty.com/ru/ui/primitives/input/switch.md) напрямую в `SettingsRow`. Состояние выбора, сведения о событии, поведение при отключении и доступе только для чтения, размер, конфигурация нативной формы, обработчики, ссылки и композиция рендеринга настраивают переключатель. `children` задаёт видимую метку строки.

Используйте `checked` и `onCheckedChange`, когда значение контролируется вашим приложением. Обработчик получает следующее состояние переключателя и сведения о событии Base UI. Нажатие на метку или переключатель вызывает его один раз. Вызовите `eventDetails.cancel()`, чтобы отклонить изменение, и не изменяйте контролируемое значение, когда изменение отменено.

```tsx theme={null}
import { useState } from 'react';
import { SettingsRow } from 'twenty-ui/components/settings';
import { IconBell } from 'twenty-ui/icon';

export const NotificationSetting = () => {
  const [enabled, setEnabled] = useState(false);

  return (
    <SettingsRow
      startElement={<IconBell aria-hidden />}
      checked={enabled}
      onCheckedChange={setEnabled}
    >
      Notifications
    </SettingsRow>
  );
};
```

Используйте `defaultChecked` для неуправляемой настройки. Пользователи клавиатуры переводят фокус на переключатель и нажимают Пробел. `disabled` отключает элемент управления и применяет к строке отключённый внешний вид. `readOnly` предотвращает изменения, сохраняя возможность фокусировки на переключателе.

```tsx theme={null}
import { SettingsRow } from 'twenty-ui/components/settings';

export const WorkspaceSettings = () => (
  <>
    <SettingsRow disabled>Notifications</SettingsRow>
    <SettingsRow readOnly defaultChecked>
      Activity history
    </SettingsRow>
  </>
);
```

## Содержимое строки и доступный текст

`children`, `startElement` и `description` принимают узлы, принадлежащие вызывающему коду. Дочерние элементы задают доступное имя переключателя, а описание задаёт его доступное описание. Не добавляйте интерактивные элементы в содержимое метки. Используйте [ListItemButton](https://docs.twenty.com/ru/ui/components/navigation/list-item-button.md) для строк действий или создайте [ListItem](https://docs.twenty.com/ru/ui/primitives/navigation/list-item.md) со ссылкой для навигации.

**Light**

[Строка настроек с описанием (light)](https://storybook.twenty.com/iframe.html?id=ui-components-settingsrow--with-description\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Строка настроек с описанием (dark)](https://storybook.twenty.com/iframe.html?id=ui-components-settingsrow--with-description\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-components-settingsrow--with-description)

```tsx theme={null}
import { SettingsRow } from 'twenty-ui/components/settings';

export const WeeklyDigestSetting = () => (
  <SettingsRow defaultChecked description="Sent every Monday" name="digest">
    Weekly digest
  </SettingsRow>
);
```

Задайте `aria-label`, `aria-labelledby` или `aria-describedby`, чтобы указать собственный доступный текст для переключателя. Явный `aria-label` заменяет созданную связь имени; явные значения `aria-labelledby` и `aria-describedby` заменяют соответствующие созданные связи.

## Нативные цели и композиция

Обычные нативные пропсы настраивают элемент управления. Для настройки метки предусмотрены два явных имени:

| Свойства | Цель |
| - | - |
| Нативные атрибуты, обработчики, `className`, `style`, `ref` и `render` | Видимый корневой элемент Switch |
| `inputRef`, `name`, `value`, `uncheckedValue`, `required` и `form` | Базовый нативный флажок Switch |
| `labelRef` и атрибуты, обработчики, классы и стили, передаваемые через `labelRender` | Внешняя нативная метка |

`htmlFor` метки управляется внутренне и следует за `id` либо за сгенерированным ID элемента управления, если ID не указан. В композиции Switch по умолчанию этот ID идентифицирует базовый флажок. При использовании `nativeButton` он идентифицирует видимую кнопку. В обоих случаях `ref` указывает на видимый корневой элемент.

Используйте `labelRender` для настройки нативной метки строки. Сохраните элемент метки и передайте пропсы колбэка рендеринга своему элементу. Его `props.children` содержит всю строку, включая переключатель. Композиция элемента объединяет его классы и стили со значениями строки по умолчанию.

```tsx theme={null}
import { useRef } from 'react';
import { SettingsRow } from 'twenty-ui/components/settings';

export const ComposedNotificationSetting = () => {
  const labelRef = useRef<HTMLLabelElement>(null);
  const controlRef = useRef<HTMLElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  return (
    <SettingsRow
      id="notification-control"
      ref={controlRef}
      inputRef={inputRef}
      nativeButton
      render={<button />}
      labelRef={labelRef}
      labelRender={<label id="notification-row" data-setting="notifications" />}
    >
      Notifications
    </SettingsRow>
  );
};
```

`onClick` получает нажатия на элемент управления. Нативные обработчики, переданные через `labelRender`, получают события метки и всплывающие события элемента управления. Вызов `preventDefault()` при нажатии на метку предотвращает её нативную активацию элемента управления. Используйте `onCheckedChange` для обновления настроек вместо определения состояния по нажатию на метку.

По умолчанию переключатель имеет `size="sm"`; используйте `"md"` для увеличенного переключателя. Высота строки остаётся прежней. `focused` применяет к строке выделенный внешний вид, не перемещая фокус клавиатуры. `className`, `style` и `render` принимают колбэки состояния Switch и настраивают элемент управления. Передавайте классы и стили метки через `labelRender`, чтобы настроить строку.

## Рендерер компонента Front

Внутри компонента Front используйте композицию с нативной кнопкой для переключателя, вложенного в метку строки:

```tsx theme={null}
import { SettingsRow } from 'twenty-ui/components/settings';

export const FrontComponentNotificationSetting = () => (
  <SettingsRow nativeButton render={<button />}>
    Notifications
  </SettingsRow>
);
```

Эта композиция активируется один раз при нажатии на метку или элемент управления. Асинхронный мост событий рендерера не может вовремя отменить активацию нативной метки хоста по умолчанию для элемента управления на основе span, что может привести к дублирующимся колбэкам изменения при прямом нажатии на элемент управления. Атрибуты валидации нативной формы, такие как `required`, также фильтруются текущим рендерером. Автономный `SettingsRow` сохраняет полный контракт формы Switch.

## Формы и сброс

`name`, `value` и `required` настраивают базовый флажок для отправки и валидации формы. Выбранный переключатель отправляет своё значение. Невыбранный переключатель не отправляет значение, если не указан `uncheckedValue`. Используйте `form`, чтобы связать ввод с формой за пределами родительского дерева строки.

Для контролируемого сброса формы восстановите принадлежащее приложению выбранное значение в обработчике `onReset` формы. Base UI 1.8 не восстанавливает неконтролируемое состояние переключателя при нативном сбросе формы. `SettingsRow` сохраняет это поведение вышестоящего компонента.

```tsx theme={null}
import { useState } from 'react';
import { SettingsRow } from 'twenty-ui/components/settings';
import { Button } from 'twenty-ui/primitives/input';

export const NotificationPreferences = () => {
  const [enabled, setEnabled] = useState(true);

  return (
    <form onReset={() => setEnabled(true)}>
      <SettingsRow
        checked={enabled}
        onCheckedChange={setEnabled}
        name="notifications"
        value="enabled"
        uncheckedValue="disabled"
      >
        Notifications
      </SettingsRow>
      <Button type="reset">Reset</Button>
    </form>
  );
};
```

## Свойства

**checked** `boolean`

Whether the switch is currently active.

To render an uncontrolled switch, use the `defaultChecked` prop instead.

**children** `ReactNode` *required*

Visible label and default accessible name of the switch. Use non-interactive node content.

**className** `string | ((state: SwitchRootState) =\> string | undefined)`

Customizes the visible Switch root and accepts a Switch state callback.

**defaultChecked** `boolean` (default: false)

Whether the switch is initially active.

To render a controlled switch, use the `checked` prop instead.

**description** `ReactNode`

Non-interactive supporting node content, used as the default accessible description of the switch.

**disabled** `boolean` (default: false)

Whether the component should ignore user interaction.

**focused** `boolean` (default: false)

Applies the highlighted row style without moving keyboard focus.

**form** `string`

Identifies the form that owns the hidden input.
Useful when the switch is rendered outside the form.

**id** `string`

Identifies the associated checkbox, or the visible root with nativeButton. The label association follows this ID.

**inputRef** `Ref\<HTMLInputElement\>`

Targets the underlying native checkbox.

**labelRef** `Ref\<HTMLLabelElement\>`

Targets the outer native label.

**labelRender** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, \{\}\>`

Customizes the outer native label with its complete composed row children. Preserve a label element and forward its props to retain control association.

**name** `string`

Identifies the field when a form is submitted.

**nativeButton** `boolean` (default: false)

Whether the component renders a native `<button>` element when replacing it
via the `render` prop.
Set to `true` if the rendered element is a native button.

**onCheckedChange** `((checked: boolean, eventDetails: \{ reason: "none"; event: Event; cancel: () =\> void; allowPropagation: () =\> void; isCanceled: boolean; isPropagationAllowed: boolean; trigger: Element | undefined; \}) =\> void)`

Receives the next checked value and Base UI event details. Controlled callers own accepted state updates; cancellation prevents a change.

**onClick** `((event: BaseUIEvent\<MouseEvent\<HTMLSpanElement, MouseEvent\>\>) =\> void)`

Native click handler for the visible Switch root.

**readOnly** `boolean` (default: false)

Whether the user should be unable to activate or deactivate the switch.

**ref** `Ref\<HTMLSpanElement\>`

Targets the visible Switch root, which defaults to a span.

**render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, SwitchRootState\>`

Customizes the visible Switch root with control props and Switch state. Use nativeButton when composing a button.

**required** `boolean` (default: false)

Whether the user must activate the switch before submitting a form.

**size** `"md" | "sm"` (default: sm)

Visual size of the switch. Defaults to sm.

**startElement** `ReactNode`

Non-interactive node content before the label.

**style** `CSSProperties | ((state: SwitchRootState) =\> CSSProperties | undefined)`

Customizes the visible Switch root and accepts a Switch state callback.

**uncheckedValue** `string`

The value submitted with the form when the switch is off.
By default, unchecked switches do not submit any value, matching native checkbox behavior.

**value** `string`

The value submitted with the form when the switch is on.
By default, switch submits the "on" value, matching native checkbox behavior.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.