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

Обзор

PhoneCountryPicker объединяет триггер с флагом страны, всплывающее окно, поиск и варианты кода вызова. Используйте полный компонент для обычного выбора или скомпонуйте Root, Trigger и Options с Dropdown, если вам нужно пользовательское всплывающее окно. Обе формы используют одни и те же подготовленные страны и выбор.

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

Предоставьте собственные данные о странах и доступное имя триггера. Используйте value с onValueChange для контролируемого выбора или defaultValue для неконтролируемого выбора. null означает, что страна не выбрана.
Каждый PhoneCountryOption имеет уникальное стабильное значение value, локализованную метку страны label, состоящий только из цифр callingCode без начального знака «плюс» и декоративный узел flag. Он также может быть disabled. Значения являются идентификаторами, принадлежащими вызывающей стороне, например кодами стран ISO, и возвращаются без изменений. Метки, флаги и коды вызова являются данными представления и не становятся выбранным идентификатором. Селектор добавляет знак «плюс» и изолирует коды вызова слева направо в строках вариантов и всплывающих подсказках при переполнении, в том числе в интерфейсах справа налево. Указывайте страны в том порядке, в котором они должны отображаться. Выбранная страна отображается первой, пока она соответствует запросу; остальные совпадения сохраняют заданный порядок.

Составная композиция

Это критическое изменение API для существующих составных вызывающих сторон. Добавьте PhoneCountryPicker.Root вокруг Dropdown.Root, переместите countries, value и onValueChange из Options в Root и удалите Trigger.country. Теперь обе части требуют Root и получают из него выбранную страну. Root управляет странами и контролируемым или неконтролируемым выбором. Поместите общий Dropdown.Root внутрь него и скомпонуйте триггер, содержимое и варианты. Trigger получает выбранный флаг и доступное описание из Root; Options считывает те же данные и выбор. Не передавайте этим частям другую страну или выбранное значение.
Используйте один корневой компонент для каждого селектора. Общий Dropdown управляет открытием, размещением всплывающего окна, страницами, фокусом и навигацией поиска. Используйте dropdownProps и contentProps в полном селекторе или настраивайте части Dropdown напрямую при составном использовании.

Поиск и выбор

Поиск находит подстроки в заданных метках стран, стабильных идентификаторах и кодах вызова. Метки и идентификаторы используют общую нормализацию normalizeSearchText: текст в нижнем регистре, декомпозицию Unicode NFD и обработку акцентов с учетом системы письма. Например, reunion соответствует Réunion, а gb соответствует идентификатору GB. Значимые различия в системах письма сохраняются согласно этой функции-помощнику. Пробелы вокруг запроса удаляются; внутренние пробелы сохраняются. При поиске по коду вызова один начальный знак «плюс» необязателен, поэтому 44, +44 и " +44 " соответствуют заданному коду вызова 44. Поиск не анализирует полный номер телефона и не определяет по нему страну. onValueChange(value, eventDetails) получает запрошенный идентификатор и общие сведения Dropdown.SelectionGroup: reason, нативный event, trigger выбранного варианта, cancel() и isCanceled. Вызовите cancel() перед обновлением контролируемого состояния, чтобы отклонить запрос. Отмененный запрос сохраняет неконтролируемый выбор и оставляет всплывающее окно открытым. Установите closeOnSelect={false}, чтобы оно оставалось открытым после принятого выбора. Изменения выбора не изменяют значение какого-либо поля ввода телефона. Установите disabled для полного селектора или Root, чтобы отключить его триггер, поиск и выбор. Отключенная страна остается видимой, и ее нельзя выбрать. Trigger.disabled и Options.disabled могут дополнительно отключать эти отдельные части.

Нативные цели и метки

Нативные атрибуты полного селектора, обработчики событий, className, style, ref, render и необязательный children применяются к его триггеру. children заменяет флаг или значок мира и шеврон по умолчанию. contentProps применяется к Dropdown.Content; optionsProps применяется к корневому div вариантов и предоставляет searchLabel, listLabel и emptyLabel. При составном использовании нативные свойства, ссылки и композиция рендеринга применяются к соответствующей кнопке Trigger или div Options. Root не рендерит узел DOM. Предоставьте локализованные метки стран и обязательный aria-label триггера. Метка выбранной страны описывает триггер, а ее флаг и шеврон являются декоративными. При пустом выборе отображается значок мира. Всплывающее окно получает имя триггера, если только его не задает Dropdown.Title или явная метка содержимого. searchLabel по умолчанию имеет значение Search и задаёт имя как поля поиска, так и его заполнителя. По умолчанию listLabel имеет значение Countries и независимо именует список. emptyLabel по умолчанию имеет значение No results.

Интеграция поля ввода телефона

Селектор поставляется без каталога стран, пакета ресурсов флагов или среды выполнения поля ввода телефона. Адаптер фронтенда управляет разбором, проверкой, форматированием телефонов, черновиками редактирования и сохранением. Сопоставьте выбранную страну библиотеки телефона с Root.value или value полного селектора и сопоставьте изменения страны обратно через один обратный вызов. Сохраняйте текст телефона в его текущем владельце при изменении или очистке страны либо при применении внешнего обновления выбранной страны. Нативная отправка формы, сброс, обязательность, режим только для чтения и интеграция Field для этого пользовательского селектора отложены. Полный селектор передает нативные атрибуты триггера согласно контракту кнопки Dropdown.

Средство рендеринга компонентов Front

Фикстуры галереи React и Preact включают полный селектор и составную композицию. Размещение портала, геометрия, прокрутка, закрытие и фокус относятся к общему Dropdown и интеграции рендерера. Селектор не вводит отдельную среду выполнения рендерера.

Свойства

string
обязательно
Required accessible name for the country selector trigger.
ReactNode
Optional trigger content replacing the default country flag or world icon and chevron.
string | ((state: PopoverTriggerState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
number
по умолчанию:"0"
How long to wait before closing the popover that was opened on hover. Specified in milliseconds.Requires the openOnHover prop.
boolean
Closes the dropdown after an accepted selection. Defaults to true.
Omit<DropdownContentProps, "children">
Props for the internally assembled Dropdown.Content, including its accessible name, placement, width and popup ref.
readonly PhoneCountryOption[]
обязательно
Prepared choices with a unique stable value, localized label, digits-only calling code without a plus sign, decorative flag node and optional disabled state. Matching choices retain their supplied order after the selected country.
string | null
Initial uncontrolled country identifier. Omit it or use null to start empty.
number
по умолчанию:"300"
How long to wait before the popover may be opened on hover. Specified in milliseconds.Requires the openOnHover prop.
boolean
Disables the trigger, search and country selection.
Omit<DropdownRootProps, "children" | "type" | "multiple">
Props for the internally assembled Dropdown.Root, including controlled open state and open-change events. The picker fixes its type to picker.
string
ID of the trigger. In addition to being forwarded to the rendered element, it is also used to specify the active trigger for the popover in controlled mode (with the PopoverRoot triggerId prop).
boolean
по умолчанию:"true"
Whether the component renders a native <button> element when replacing it via the render prop. Set to false if the rendered element is not a button (e.g. <div>).
((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) => void)
Receives the requested country identifier or null and Dropdown.SelectionGroup event details, including reason, event, trigger and cancel(). Cancel before updating controlled state to reject a selection.
boolean
по умолчанию:"false"
Whether the popover should also open when the trigger is hovered.
PhoneCountryPickerOptionsProps
Props for the options root div, including native attributes, ref, render, searchLabel, listLabel and emptyLabel. Search matches normalized labels and identifiers, or calling codes with an optional leading plus sign. Surrounding query whitespace is trimmed.
Ref<HTMLButtonElement>
Ref to the trigger button, or the element composed through render.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, PopoverTriggerState>
Composes the trigger with an element or render callback. Native attributes, handlers, className, style and ref target the trigger.
CSSProperties | ((state: PopoverTriggerState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
string | null
Controlled country identifier. Use null to clear the selection. Labels and calling codes do not replace this value.

PhoneCountryPicker.Root

ReactNode
обязательно
A Dropdown.Root with type=“picker”, its Trigger, Content and Options. Root shares prepared data and selection and renders no DOM node.
boolean
по умолчанию:"true"
Closes the composed Dropdown after an accepted selection. Defaults to true.
readonly PhoneCountryOption[]
обязательно
Prepared choices shared by Trigger and Options, with unique stable values, localized labels, digits-only calling codes without a plus sign, decorative flag nodes and optional disabled states.
string | null
по умолчанию:"null"
Initial uncontrolled country identifier. Omit it or use null to start empty.
boolean
по умолчанию:"false"
Disables the composed trigger, search and country selection.
((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) => void)
Receives the requested identifier or null and Dropdown.SelectionGroup event details, including reason, event, trigger and cancel(). Cancel before updating controlled state to reject a selection.
string | null
Controlled country identifier shared by the parts. Use null to clear the selection.

PhoneCountryPicker.Trigger

string
обязательно
Required accessible name for the country selector button.
ReactNode
Optional trigger content replacing the selected country flag or empty world icon and chevron. The selected label comes from Root.
string | ((state: PopoverTriggerState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
number
по умолчанию:"0"
How long to wait before closing the popover that was opened on hover. Specified in milliseconds.Requires the openOnHover prop.
number
по умолчанию:"300"
How long to wait before the popover may be opened on hover. Specified in milliseconds.Requires the openOnHover prop.
boolean
Disables the native trigger button in addition to Root.disabled.
string
ID of the trigger. In addition to being forwarded to the rendered element, it is also used to specify the active trigger for the popover in controlled mode (with the PopoverRoot triggerId prop).
boolean
по умолчанию:"true"
Whether the component renders a native <button> element when replacing it via the render prop. Set to false if the rendered element is not a button (e.g. <div>).
boolean
по умолчанию:"false"
Whether the popover should also open when the trigger is hovered.
Ref<HTMLButtonElement>
Ref to the trigger button, or the element composed through render.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, PopoverTriggerState>
Composes the Dropdown trigger with an element or render callback. Native attributes, handlers, className, style and ref target this element.
CSSProperties | ((state: PopoverTriggerState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

PhoneCountryPicker.Options

boolean
Disables search and selection in addition to Root.disabled.
string
по умолчанию:"No results"
Status message shown when no country label, identifier or calling code matches. Defaults to No results.
string
по умолчанию:"Countries"
Accessible name of the country listbox, separate from the search field. Defaults to Countries.
Ref<HTMLDivElement>
Ref to the options root div, or the element composed through render.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, {}>
Composes the non-interactive options root with an element or render callback. Native attributes, handlers, className, style and ref target this element. searchLabel names the internal search input.
string
по умолчанию:"Search"
Accessible name and placeholder of the country search field. Defaults to Search. Search matches normalized labels and identifiers, or calling codes with an optional leading plus sign. Surrounding query whitespace is trimmed.