Button
Кнопка запускает действие в ответ на нажатие.
Когда использовать
Button запускает действие: сохраняет данные, открывает окно, добавляет запись или отправляет форму. Подпись должна объяснять результат нажатия: «Сохранить изменения» понятнее, чем «ОК».
- Основная кнопка выделяет главное действие. В одной группе действий обычно достаточно одной основной кнопки.
- Обычные кнопки подходят для равнозначных действий; текстовые — для второстепенных.
- Пунктирную кнопку удобно использовать для добавления элемента.
- Для перехода на другую страницу передайте
href: компонент создаст настоящую ссылку. Если пользователь выбирает одно из значений, рассмотрите Radio или Select.
CSS-префиксы Button показывают общий ConfigProvider.prefixCls и локальный prefixCls без сброса состояния. Локальный prefixCls — полный префикс кнопки, без автоматического добавления -btn. Контейнер кнопок и служебные переменные используют общий префикс провайдера.
Как выбрать оформление
Начните с роли действия, затем выберите оформление. type задаёт готовый вариант; color и variant позволяют настроить цвет и способ отображения отдельно.
| Задача | Настройка | Работающий пример |
|---|---|---|
| Главное действие | type="primary" |
Типы кнопок |
| Равнозначное действие | type="default" |
Несколько кнопок |
| Добавить элемент | type="dashed" |
Типы кнопок |
| Второстепенное действие | type="text" |
Типы кнопок |
| Свой цвет и заливка | color и variant |
Цвет и вариант |
type="primary" соответствует сочетанию color="primary" variant="solid". Явные color и variant имеют приоритет. Для удаления и других действий с риском используйте danger; если одновременно задаёте color, учитывайте его приоритет.
ghost меняет оформление кнопки на сложном фоне, а block растягивает её на ширину контейнера. Размер задаётся через size или общие настройки ConfigProvider. Эти свойства не меняют смысл действия и способ обработки события.
Иконка передаётся через icon как Svelte snippet; iconPlacement задаёт сторону. Для кнопки только со значком укажите доступное имя через aria-label. Пример иконок содержит обе композиции и их исходный код.
Действия, ссылки и ожидание
Без href компонент создаёт нативный button. Его htmlType по умолчанию равен button, поэтому он не отправляет окружающую форму случайно. Для отправки Form используйте htmlType="submit", для сброса — htmlType="reset".
С href создаётся нативный a: работают открытие в новой вкладке, копирование адреса, target и rel. Само оформление type="link" без href остаётся кнопкой действия. Пример состояний показывает переход и обработчик нажатия.
Обработчик onclick получает нативное событие. Для отмены перехода ссылки вызовите event.preventDefault(). bind:nativeElement предоставляет кнопку или ссылку после mount; при SSR DOM-элемента ещё нет.
Состояние loading принадлежит приложению: включите его перед запросом и выключите после завершения. Объект loading позволяет отложить появление индикатора через delay, чтобы короткая операция не мигала. Компонент не запускает запрос и не отслеживает Promise обработчика. Загрузка показывает переключение и задержку.
У кнопки без своей иконки штатный индикатор плавно появляется и исчезает. theme.token.motion=false и prefers-reduced-motion отключают этот переход. При гидратации кнопка и ссылка сохраняют фокус.
Для отдельной настройки темы используйте токены оформления (design tokens) Button, а для конкретной части кнопки — поддерживаемые classNames и styles из Semantic DOM. В styles передаются CSS-строки; объект JavaScript со свойствами CSS здесь не используется.
Примеры
Типы кнопок
Основная, обычная, пунктирная, текстовая кнопка и ссылка. Выделяйте основным стилем главное действие.
<script lang="ts">
import { Button } from '@woodger/antd';
let action = $state(('Нажмите кнопку, чтобы проверить действие.'));
const buttons = [
{ type: 'primary', label: 'Основная', message: 'Нажата основная кнопка.' },
{ type: 'default', label: 'Обычная', message: 'Нажата обычная кнопка.' },
{ type: 'dashed', label: 'Пунктирная', message: 'Нажата пунктирная кнопка.' },
{ type: 'text', label: 'Текстовая', message: 'Нажата текстовая кнопка.' },
{ type: 'link', label: 'Ссылка', message: 'Нажата кнопка-ссылка.' }
] as const;
</script>
<style>
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.status-line {
margin-top: 16px;
color: var(--ant-color-text-secondary);
font-size: 12px;
}
</style>
<div class="row">
{#each buttons as button (button.type)}
<Button type={button.type} onclick={() => { action = button.message; }}>{(button.label)}</Button>
{/each}
</div>
<div class="status-line" role="status">{action}</div>
Цвета и варианты
Цвет color и вариант variant задаются независимо: заливка, рамка, пунктир, текст или ссылка.
<script lang="ts">
import { onMount } from 'svelte';
import { Button, ConfigProvider } from '@woodger/antd';
let isWide = $state(false);
const colors = ['default', 'primary', 'danger', 'pink', 'purple', 'cyan'] as const;
const variants = ['solid', 'outlined', 'dashed', 'filled', 'text', 'link'] as const;
onMount(() => {
const query = window.matchMedia('(min-width: 1600px)');
const updateSize = () => { isWide = query.matches; };
updateSize();
query.addEventListener('change', updateSize);
return () => query.removeEventListener('change', updateSize);
});
</script>
<style>
.matrix {
display: grid;
gap: 16px;
}
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
</style>
<ConfigProvider componentSize={isWide ? 'medium' : 'small'}>
<div class="matrix">
{#each colors as color (color)}
<div class="row" role="group" aria-label={("Цвет " + String((color)) + "")}>
{#each variants as variant (variant)}
<Button
{color}
{variant}
aria-label={("" + String((color)) + ": " + String((variant)) + "")}
>{(variant)}</Button>
{/each}
</div>
{/each}
</div>
</ConfigProvider>
Иконки
Передайте иконку через snippet icon. Кнопке без текста задайте доступное имя через aria-label.
<script lang="ts">
import { Button, Tooltip } from '@woodger/antd';
</script>
<style>
.stack {
display: grid;
gap: 16px;
}
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
</style>
{#snippet searchIcon()}
<svg width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="1.75" aria-hidden="true" focusable="false" style="display:block">
<circle cx="10.5" cy="10.5" r="7" /><path d="m16 16 5 5" />
</svg>
{/snippet}
<div class="stack">
<div class="row">
<Tooltip title={("Поиск")}><Button type="primary" shape="circle" icon={searchIcon}
aria-label={("Поиск, основная круглая")} /></Tooltip>
<Button type="primary" shape="circle">A</Button>
<Button type="primary" icon={searchIcon}>{("Поиск")}</Button>
<Tooltip title={("Поиск")}><Button shape="circle" icon={searchIcon}
aria-label={("Поиск, круглая")} /></Tooltip>
<Button icon={searchIcon}>{("Поиск")}</Button>
</div>
<div class="row">
<Tooltip title={("Поиск")}><Button shape="circle" icon={searchIcon}
aria-label={("Поиск, дополнительная круглая")} /></Tooltip>
<Button icon={searchIcon}>{("Поиск")}</Button>
<Tooltip title={("Поиск")}><Button type="dashed" shape="circle" icon={searchIcon}
aria-label={("Поиск, пунктирная круглая")} /></Tooltip>
<Button type="dashed" icon={searchIcon}>{("Поиск")}</Button>
<Button href={("/ant-design#overview")} icon={searchIcon} aria-label={("Перейти к обзору с иконкой")} />
</div>
</div>
Расположение иконки
iconPlacement размещает иконку до или после подписи. Положение индикатора загрузки меняется вместе с ней.
<script lang="ts">
import { Button, Divider, RadioGroup, Tooltip } from '@woodger/antd';
let position = $state<'start' | 'end'>('end');
</script>
<style>
.stack {
display: grid;
gap: 16px;
}
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
</style>
{#snippet searchIcon()}
<svg width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="1.75" aria-hidden="true" focusable="false" style="display:block">
<circle cx="10.5" cy="10.5" r="7" /><path d="m16 16 5 5" />
</svg>
{/snippet}
<div class="stack">
<RadioGroup
aria-label={("Расположение иконки")}
optionType="button"
value={position}
options={([{ value: 'start', label: 'В начале' }, {
value: 'end',
label: 'В конце'
}])}
onValueChange={value => { if (value === 'start' || value === 'end') position = value; }}
/>
<Divider titlePlacement="start" plain>{("Предпросмотр")}</Divider>
<div class="row">
<Tooltip title={("Поиск")}><Button type="primary" shape="circle" icon={searchIcon}
aria-label={("Поиск, основная круглая")} /></Tooltip>
<Button type="primary" shape="circle">A</Button>
<Button
type="primary"
icon={searchIcon}
iconPlacement={position}
>{("Поиск")}</Button>
<Tooltip title={("Поиск")}><Button shape="circle" icon={searchIcon}
aria-label={("Поиск, круглая")} /></Tooltip>
<Button icon={searchIcon} iconPlacement={position}>{("Поиск")}</Button>
</div>
<div class="row">
<Tooltip title={("Поиск")}><Button shape="circle" icon={searchIcon}
aria-label={("Поиск, дополнительная круглая")} /></Tooltip>
<Button type="text" icon={searchIcon} iconPlacement={position}>{("Поиск")}</Button>
<Tooltip title={("Поиск")}><Button type="dashed" shape="circle" icon={searchIcon}
aria-label={("Поиск, пунктирная круглая")} /></Tooltip>
<Button
type="dashed"
icon={searchIcon}
iconPlacement={position}
>{("Поиск")}</Button>
<Button href={("/ant-design#overview")} icon={searchIcon} iconPlacement={position}
aria-label={("Перейти к обзору с иконкой")} />
<Button type="primary" loading iconPlacement={position}>{("Загрузка")}</Button>
</div>
</div>
Размеры
Три размера кнопок: large, medium и small. Размер можно задать отдельно или через ConfigProvider.
<script lang="ts">
import { Button, Divider, RadioGroup } from '@woodger/antd';
let size = $state<'large' | 'medium' | 'small'>('large');
</script>
<style>
.stack {
display: grid;
gap: 16px;
}
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
</style>
{#snippet downloadIcon()}
<svg width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="1.75" aria-hidden="true" focusable="false" style="display:block">
<path d="M12 3v12m-4-4 4 4 4-4M5 17v4h14v-4" />
</svg>
{/snippet}
<div class="stack">
<RadioGroup
aria-label={("Размер кнопок в примере")}
optionType="button"
value={size}
options={([
{ value: 'large', label: 'Большой' },
{ value: 'medium', label: 'Средний' },
{ value: 'small', label: 'Маленький' }
])}
onValueChange={value => {
if (value === 'large' || value === 'medium' || value === 'small') size = value;
}}
/>
<Divider titlePlacement="start" plain>{("Предпросмотр")}</Divider>
<div class="row">
<Button type="primary" {size}>{("Основная")}</Button>
<Button {size}>{("Обычная")}</Button>
<Button type="dashed" {size}>{("Пунктирная")}</Button>
</div>
<div><Button type="link" {size}>{("Ссылка")}</Button></div>
<div class="row">
<Button type="primary" {size} icon={downloadIcon} aria-label={("Скачать, без подписи")} />
<Button type="primary" shape="circle" {size} icon={downloadIcon} aria-label={("Скачать, круглая")} />
<Button type="primary" shape="round" {size} icon={downloadIcon} aria-label={("Скачать, скруглённая")} />
<Button
type="primary"
shape="round"
{size}
icon={downloadIcon}
>{("Скачать")}</Button>
<Button type="primary" {size} icon={downloadIcon}>{("Скачать")}</Button>
</div>
</div>
Недоступные кнопки
disabled запрещает действие для каждого типа кнопки, включая кнопку со ссылкой.
<script lang="ts">
import { Button } from '@woodger/antd';
const types = [
{ value: 'primary', label: 'Основная' },
{ value: 'default', label: 'Обычная' },
{ value: 'dashed', label: 'Пунктирная' },
{ value: 'text', label: 'Текстовая' },
{ value: 'link', label: 'Ссылка' }
] as const;
</script>
<style>
.stack {
display: grid;
gap: 16px;
}
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.row :global(button), .row :global(a) {
max-inline-size: 100%;
min-block-size: min-content;
white-space: normal;
}
.ghost-row {
padding: 16px;
border-radius: 6px;
background: rgb(190, 200, 200);
}
</style>
<div class="stack">
{#each types as type (type.value)}
<div class="row">
<Button type={type.value}>{(type.label)}</Button>
<Button
type={type.value}
disabled
>{(type.label)}{(" (недоступна)")}</Button>
</div>
{/each}
<div class="row">
<Button type="primary" href={("/ant-design#overview")}>
{("Ссылка с href")}
</Button>
<Button type="primary" href={("/ant-design#overview")} disabled>
{("Ссылка с href (недоступна)")}
</Button>
</div>
<div class="row">
<Button danger>{("Опасное действие")}</Button>
<Button danger disabled>{("Опасное действие (недоступна)")}</Button>
</div>
<div class="row">
<Button danger type="text">{("Опасный текст")}</Button>
<Button danger type="text" disabled>{("Опасный текст (недоступна)")}</Button>
</div>
<div class="row">
<Button danger type="link">{("Опасная ссылка")}</Button>
<Button danger type="link" disabled>{("Опасная ссылка (недоступна)")}</Button>
</div>
<div class="row ghost-row">
<Button ghost>{("Прозрачная")}</Button>
<Button ghost disabled>{("Прозрачная (недоступна)")}</Button>
</div>
</div>
Загрузка
Исходные варианты индикатора и дополнительный пример с задержкой. Свой snippet заменяет spinner; в v1 кнопка во время загрузки недоступна.
<script lang="ts">
import { onDestroy } from 'svelte';
import { Button } from '@woodger/antd';
let active = $state([false, false, false, false, false]);
const timers = new Map<number, ReturnType<typeof setTimeout>>();
function startLoading(index: number) {
if (active[index]) {
return;
}
active[index] = true;
timers.set(index, setTimeout(() => {
active[index] = false;
timers.delete(index);
}, 3000));
}
onDestroy(() => {
for (const timer of timers.values()) clearTimeout(timer);
timers.clear();
});
</script>
<style>
.stack {
display: grid;
gap: 16px;
}
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.row :global(button) {
max-inline-size: 100%;
min-block-size: min-content;
white-space: normal;
}
.spinner {
display: block;
animation: spin 1s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .spinner { animation: none; } }
</style>
{#snippet powerIcon()}
<svg width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="1.75" aria-hidden="true" focusable="false" style="display:block">
<path d="M12 2v10m-6.4-6.4a9 9 0 1 0 12.8 0" />
</svg>
{/snippet}
{#snippet customSpinner()}
<svg class="spinner" width="1em" height="1em" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="1.75" aria-hidden="true" focusable="false">
<path d="M20 12a8 8 0 1 1-2.3-5.7M18 2v5h-5" />
</svg>
{/snippet}
<div class="stack">
<div class="row">
<Button type="primary" loading>{("Загрузка")}</Button>
<Button type="primary" size="small" loading>{("Загрузка")}</Button>
<Button type="primary" loading icon={powerIcon} aria-label={("Загрузка без подписи")} />
<Button
type="primary"
loading={{ icon: customSpinner }}
>{("Свой индикатор")}</Button>
</div>
<div class="row">
<Button type="primary" loading={active[0]} onclick={() => startLoading(0)}>
{("\n Запустить загрузку\n ")}
</Button>
<Button
type="primary"
loading={active[1]}
iconPlacement="end"
onclick={() => startLoading(1)}
>{("\n Индикатор справа\n ")}</Button>
<Button
type="primary"
loading={active[2]}
icon={powerIcon}
onclick={() => startLoading(2)}
>{("\n Заменить иконку\n ")}</Button>
<Button
type="primary"
loading={active[3]}
icon={powerIcon}
aria-label={("Запустить загрузку без подписи")}
onclick={() => startLoading(3)}
/>
<Button type="primary" loading={active[3] ? { icon: customSpinner } : false} icon={powerIcon}
onclick={() => startLoading(3)}>{("Свой индикатор при нажатии")}</Button>
</div>
<div class="row">
<Button type="primary" loading={active[4] ? { delay: 500 } : false}
onclick={() => startLoading(4)}>{("С задержкой")}</Button>
</div>
</div>
Несколько действий
Оставьте основное действие на виду, а дополнительные объедините в Dropdown. SpaceCompact соединяет соседние кнопки.
<script lang="ts">
import { Button, Dropdown, SpaceCompact } from '@woodger/antd';
let action = $state(('Выберите действие в меню.'));
const items = [
{ key: 'first', label: 'Первое действие' },
{ key: 'second', label: 'Второе действие' },
{ key: 'third', label: 'Третье действие' }
];
</script>
<style>
.row {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
}
output {
display: block;
margin-top: 16px;
color: var(--ant-color-text-secondary);
font-size: 12px;
}
</style>
{#snippet moreIcon()}
<svg width="1em" height="1em" viewBox="0 0 24 24" fill="currentColor"
aria-hidden="true" focusable="false" style="display:block">
<circle cx="5" cy="12" r="1.6" /><circle cx="12" cy="12" r="1.6" />
<circle cx="19" cy="12" r="1.6" />
</svg>
{/snippet}
{#snippet actionButton()}<Button onclick={() => {
action = ('Выполнено основное действие.');
}}>{("Действия")}</Button>{/snippet}
{#snippet moreButton()}
<Dropdown trigger={['click']} placement="bottomRight" menu={({
items,
onClick: ({ key }) => {
const item = items.find(item => item.key === key);
const label = item?.label ?? key;
action = ("Выбрано: " + String((label)) + "");
}
})}>
<Button icon={moreIcon} aria-label={("Дополнительные действия")} />
</Dropdown>
{/snippet}
<div class="row">
<Button type="primary">{("Основная")}</Button>
<Button>{("Дополнительная")}</Button>
<SpaceCompact items={([actionButton, moreButton])} />
</div>
<output aria-label={("Выбранное действие")}>{action}</output>
Прозрачные кнопки
ghost убирает заливку. Такой вариант подходит для цветного или другого сложного фона.
<script lang="ts">
import { Button } from '@woodger/antd';
</script>
<style>
.preview {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
padding: 16px;
border-radius: 6px;
background: rgb(190, 200, 200);
}
</style>
<div class="preview">
<Button type="primary" ghost>{("Основная")}</Button>
<Button ghost>{("Обычная")}</Button>
<Button type="dashed" ghost>{("Пунктирная")}</Button>
<Button danger ghost>{("Опасное действие")}</Button>
</div>
Опасные действия
danger выделяет действия, требующие внимания: например, удаление данных.
<script lang="ts">
import { Button } from '@woodger/antd';
</script>
<style>
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
</style>
<div class="row">
<Button type="primary" danger>{("Основная")}</Button>
<Button danger>{("Обычная")}</Button>
<Button type="dashed" danger>{("Пунктирная")}</Button>
<Button type="text" danger>{("Текстовая")}</Button>
<Button type="link" danger>{("Ссылка")}</Button>
</div>
На всю ширину
block растягивает кнопку на ширину родительского контейнера.
<script lang="ts">
import { Button } from '@woodger/antd';
</script>
<style>
.stack {
display: grid;
gap: 8px;
}
</style>
<div class="stack">
<Button type="primary" block>{("Основная")}</Button>
<Button block>{("Обычная")}</Button>
<Button type="dashed" block>{("Пунктирная")}</Button>
<Button disabled block>{("Недоступна")}</Button>
<Button type="text" block>{("Текстовая")}</Button>
<Button type="link" block>{("Ссылка")}</Button>
</div>
Градиент
Собственное оформление основной кнопки через ConfigProvider.button.class и CSS, включая состояние наведения.
<script lang="ts">
import { Button, ConfigProvider } from '@woodger/antd';
</script>
<style>
.preview {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.preview :global(.gradient-button.ant-btn-primary:not([disabled])) { position: relative; }
.preview :global(.gradient-button.ant-btn-primary:not([disabled]) > span) { position: relative; }
.preview :global(.gradient-button.ant-btn-primary:not([disabled])::before) {
content: '';
position: absolute;
inset: -1px;
border-radius: inherit;
background: linear-gradient(135deg, #6253e1, #04befe);
opacity: 1;
transition: opacity var(--ant-motion-duration-slow);
}
.preview :global(.gradient-button.ant-btn-primary:not([disabled]):hover::before) { opacity: 0; }
@media (prefers-reduced-motion: reduce) {
.preview :global(.gradient-button::before) { transition: none; }
}
</style>
{#snippet downloadIcon()}
<svg width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="1.75" aria-hidden="true" focusable="false" style="display:block">
<path d="M12 3v12m-4-4 4 4 4-4M5 17v4h14v-4" />
</svg>
{/snippet}
<div class="preview">
<ConfigProvider button={{ class: 'gradient-button' }}>
<div class="preview">
<Button type="primary" icon={downloadIcon}>{("Градиент")}</Button>
<Button>{("Обычная")}</Button>
</div>
</ConfigProvider>
</div>
Своя волна
ConfigProvider.wave отключает стандартную волну или заменяет её своим эффектом. Пример учитывает reduced motion.
<script lang="ts">
import { onDestroy } from 'svelte';
import { Button, ConfigProvider, type ShowWaveEffect } from '@woodger/antd';
let effect = $state(('Нажмите кнопку, чтобы сравнить эффекты.'));
const animations = new Set<Animation>();
const holders = new Set<HTMLElement>();
function playAnimation(node: HTMLElement, frames: Keyframe[], cleanup = () => {}) {
const animation = node.animate(frames, { duration: 500, easing: 'ease-out' });
animations.add(animation);
const finish = () => {
animations.delete(animation);
cleanup();
};
void animation.finished.then(finish, finish);
}
const showInsetEffect: ShowWaveEffect = (node, { component, event }) => {
if (component !== 'Button') {
return;
}
effect = ('Внутренняя волна');
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
return;
}
const rect = node.getBoundingClientRect();
const x = event.detail === 0 ? rect.width / 2 : event.clientX - rect.left;
const y = event.detail === 0 ? rect.height / 2 : event.clientY - rect.top;
const diameter = Math.hypot(rect.width, rect.height) * 2;
const holder = document.createElement('span');
holder.setAttribute('aria-hidden', 'true');
holder.style.cssText = `
position: absolute;
inset: 0;
overflow: hidden;
border-radius: inherit;
pointer-events: none;
z-index: 1;
`;
const dot = document.createElement('span');
dot.style.cssText = `
position: absolute;
left: ${x}px;
top: ${y}px;
width: ${diameter}px;
height: ${diameter}px;
border-radius: 50%;
background: rgba(255,255,255,0.65);
pointer-events: none;
`;
holder.append(dot);
node.append(holder);
holders.add(holder);
playAnimation(dot, [
{
transform: 'translate(-50%, -50%) scale(0)',
opacity: 1
},
{
transform: 'translate(-50%, -50%) scale(1)',
opacity: 0
}
], () => {
holder.remove();
holders.delete(holder);
});
};
const showShakeEffect: ShowWaveEffect = (node, { component }) => {
if (component !== 'Button') {
return;
}
effect = ('Встряхивание');
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
return;
}
for (const animation of node.getAnimations()) {
if (animations.has(animation)) animation.cancel();
}
playAnimation(node, [0, -12, 12, -5, 5, 0].map(angle => ({
transform: `rotate(${angle}deg)`
})));
};
onDestroy(() => {
for (const animation of animations) animation.cancel();
for (const holder of holders) holder.remove();
animations.clear();
holders.clear();
});
</script>
<style>
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 16px;
}
output {
display: block;
margin-top: 16px;
color: var(--ant-color-text-secondary);
font-size: 12px;
}
</style>
<div class="row">
<ConfigProvider wave={{ disabled: true }}>
<Button type="primary" onclick={() => { effect = ('Волна отключена'); }}>
{("Без волны")}
</Button>
</ConfigProvider>
<ConfigProvider>
<Button
type="primary"
onclick={() => { effect = ('Стандартная волна'); }}
>{("Стандартная")}</Button>
</ConfigProvider>
<ConfigProvider wave={{ showEffect: showInsetEffect }}>
<Button type="primary">{("Внутренняя волна")}</Button>
</ConfigProvider>
<ConfigProvider wave={{ showEffect: showShakeEffect }}>
<Button type="primary">{("Встряхивание")}</Button>
</ConfigProvider>
</div>
<output aria-label={("Эффект волны")}>{effect}</output>
Фон недоступных кнопок
Токены defaultBgDisabled и dashedBgDisabled меняют фон недоступных кнопок через тему ConfigProvider.
<script lang="ts">
import { Button, ConfigProvider } from '@woodger/antd';
</script>
<style>
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
</style>
<ConfigProvider theme={{
cssVar: {},
components: {
Button: {
defaultBgDisabled: 'rgba(0,0,0,0.1)',
dashedBgDisabled: 'rgba(0,0,0,0.4)'
}
}
}}>
<div class="row">
<Button type="primary" disabled>{("Основная")}</Button>
<Button disabled>{("Обычная")}</Button>
<Button type="dashed" disabled>{("Пунктирная")}</Button>
</div>
</ConfigProvider>
Семантические стили
classNames и styles оформляют root и content. styles принимает объект или функцию от свойств кнопки.
<script lang="ts">
import { Button, type ButtonProps } from '@woodger/antd';
const classNames = { root: 'semantic-root', content: 'semantic-content' };
const styles: ButtonProps['styles'] = info => info.props.type === 'primary'
? {
root: `
background: #171717;
border-color: #171717;
`,
content: 'color:#fff'
}
: {};
</script>
<style>
.preview {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.preview :global(.semantic-root) {
height: auto;
padding: 8px 16px;
border-radius: var(--ant-border-radius);
}
.preview :global(.semantic-content) { font-weight: 500; }
</style>
<div class="preview">
<Button {classNames} styles={{ root: 'box-shadow:0 1px 2px rgba(0,0,0,0.05)' }}>
{("Объект")}
</Button>
<Button type="primary" {classNames} {styles}>{("Функция")}</Button>
</div>
Цветное действие и группа кнопок
Цветное действие, ссылка и кнопки счётчика в Flex. Размер и оформление кнопок счётчика задаёт ConfigProvider.
<script lang="ts">
import { Button, ConfigProvider, Flex } from '@woodger/antd';
let clicks = $state(0);
</script>
<Flex gap={8} align="center" wrap>
<Button color="purple" variant="filled" iconPlacement="end" onclick={() => { clicks++; }}>
{#snippet icon()}
<span aria-hidden="true">★</span>
{/snippet}{("\n Цветное действие (")}{clicks})
</Button>
<Button href={("/ant-design#overview")}>{("Перейти к обзору")}</Button>
<ConfigProvider componentSize="small" button={{ color: 'green', variant: 'outlined' }}>
<Flex gap={8}>
<Button onclick={() => { clicks--; }}>−</Button>
<Button onclick={() => { clicks++; }}>+</Button>
</Flex>
</ConfigProvider>
</Flex>
prefixCls задаёт полный префикс кнопки без добавления суффикса -btn.
Контейнер кнопок и служебные переменные используют общий префикс провайдера.
CSS-префиксы Button
Общий namespace ConfigProvider и локальный prefixCls; состояние компонента сохраняется при смене имени.
<script lang="ts">
import { Button, Checkbox, ConfigProvider, Flex } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-btn' : '');
let clicks = $state(0);
</script>
<style>
.example,
.prefix-stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("Общий префикс Button suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Локальный префикс Button")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'button-theme' } }}>
<div class="prefix-stage">
<Flex gap={8} wrap>
<Button prefixCls={localPrefix} type="primary" onclick={() => clicks++}>
{("Сохранить с префиксом")}
</Button>
<Button prefixCls={localPrefix} onclick={() => clicks = 0}>
{("Сбросить счётчик")}
</Button>
</Flex>
<output
aria-label={("Действия Button с префиксом")}
>{("Действий: ")}{clicks}</output>
</div>
</ConfigProvider>
<output
aria-label={("CSS-префикс Button")}
>{("Общий: ")}{prefix}{("; локальный: ")}{(localPrefix
|| ('из провайдера'))}</output>
<p>
<code>prefixCls</code> {("задаёт полный префикс кнопки без добавления суффикса")} <code>-btn</code>.
{("Контейнер кнопок и служебные переменные используют общий префикс провайдера.")}
</p>
</div>
API
Основные параметры для работы с Button. Точные сигнатуры доступны в публичных типах
ButtonProps, ButtonLinkProps и ButtonConfig
установленного пакета @woodger/antd.
| Свойство | Описание | Тип | По умолчанию |
|---|---|---|---|
prefixCls | Полный CSS-префикс компонента и его частей. Непустой локальный prop приоритетнее; пустая строка и undefined наследуют ConfigProvider. Namespace темы задаётся отдельно. | ButtonProps['prefixCls'] | ant-btn |
type | Готовое оформление: primary, default, dashed, text или link. | ButtonProps['type'] | default |
color | Цвет кнопки: default, primary, danger или один из preset-цветов. | ButtonProps['color'] | default |
variant | Вариант оформления: solid, outlined, dashed, filled, text или link. | ButtonProps['variant'] | outlined |
danger | Выделяет опасное действие. Явная пара color + variant имеет приоритет. | ButtonProps['danger'] | false |
ghost | Прозрачный фон для сложной подложки; применяется к кнопкам с рамкой или заливкой. | ButtonProps['ghost'] | false |
block | Растягивает кнопку на ширину родительского контейнера. | ButtonProps['block'] | false |
size | small, medium или large. Без локального size наследует ConfigProvider. | ButtonProps['size'] | medium |
shape | default, circle, round или square. | ButtonProps['shape'] | default |
children | Подпись или Svelte snippet с содержимым кнопки. | ButtonProps['children'] | — |
icon | Иконка как snippet или другое ButtonContent. | ButtonProps['icon'] | — |
iconPlacement | Положение иконки: start или end. | ButtonProps['iconPlacement'] | start |
loading | boolean или объект с delay в миллисекундах и собственным icon. Для v1 активная загрузка делает native button недоступной. | ButtonProps['loading'] | false |
disabled | Запрещает действие. Для href убирает переход и исключает ссылку из Tab-порядка. | ButtonProps['disabled'] | false |
href | Создаёт нативную ссылку вместо button. Без href type="link" остаётся кнопкой действия. | ButtonLinkProps['href'] | — |
target | Цель навигации ссылки; rel, download и referrerpolicy также передаются нативному элементу. | ButtonProps['target'] | — |
htmlType | Нативный тип кнопки: button, submit или reset. По умолчанию button. | ButtonProps['htmlType'] | button |
onclick | Нативное событие Svelte. Для ссылки тип обработчика определяется ButtonLinkProps. | ButtonProps['onclick'] | — |
classNames | Классы semantic slots root, icon и content: объект или callback от { props }. | ButtonProps['classNames'] | — |
styles | CSS-строки для semantic slots: объект или callback от { props }. | ButtonProps['styles'] | — |
autoInsertSpace | Автоматический интервал между двумя китайскими иероглифами; по умолчанию включён. | ButtonProps['autoInsertSpace'] | true |
nativeElement | bind:nativeElement получает нативную кнопку или ссылку после mount; при unmount ссылка очищается. | ButtonProps['nativeElement'] | — |
onclick имеет приоритет над совместимым onClick.
Для href обработчик получает нативное событие ссылки.
Нативные атрибуты, включая form, name, value
и aria-*, передаются элементу.
Preset Colors
bluepurplecyangreenmagentapinkredorangeyellowvolcanogeekbluelimegoldConfigProvider.button
Общие настройки кнопок принимают поля публичного ButtonConfig:
autoInsertSpacecolorvariantshapeloadingIconclassstyleclassNamesstyles
Локальные параметры Button имеют приоритет. iconPlacement задаёт положение иконки;
SpaceCompact объединяет соседние кнопки в компактную группу.
Semantic DOM
Выберите элемент, чтобы увидеть его границу на настоящей кнопке.
Эти имена используются в classNames и styles.
classNames назначает CSS-классы, а styles принимает CSS-строки.
Оба параметра поддерживают объект или функцию от { props }. Пример семантических стилей показывает оба варианта.
Токены оформления
Компонентные настройки передаются через ConfigProvider.theme.components.Button.
Их имена проверяются по публичному ComponentTokenMap['Button'].
<script lang="ts">
import { Button, ConfigProvider } from '@woodger/antd';
</script>
<ConfigProvider theme={{
cssVar: {},
components: {
Button: {
defaultBg: '#f6ffed',
defaultColor: '#389e0d',
defaultBorderColor: '#b7eb8f',
contentFontSize: 16
}
}
}}>
<Button>{("Своя тема Button")}</Button>
</ConfigProvider>
| Токен | Назначение |
|---|---|
fontWeight | Насыщенность текста. |
iconGap | Расстояние между иконкой и подписью. |
defaultShadow | Тень обычной кнопки. |
primaryShadow | Тень основной кнопки. |
dangerShadow | Тень опасной кнопки. |
primaryColor | Цвет текста основной кнопки. |
defaultColor | Цвет текста обычной кнопки. |
defaultBg | Фон обычной кнопки. |
defaultBorderColor | Рамка обычной кнопки. |
dangerColor | Цвет текста опасной кнопки. |
defaultHoverBg | Фон при наведении. |
defaultHoverColor | Цвет текста при наведении. |
defaultHoverBorderColor | Рамка при наведении. |
defaultActiveBg | Фон при нажатии. |
defaultActiveColor | Цвет текста при нажатии. |
defaultActiveBorderColor | Рамка при нажатии. |
defaultGhostColor | Цвет текста прозрачной кнопки. |
ghostBg | Фон прозрачной кнопки. |
defaultGhostBorderColor | Рамка прозрачной кнопки. |
solidTextColor | Цвет текста кнопки с заливкой. |
textTextColor | Цвет текста текстовой кнопки. |
textTextHoverColor | Цвет текста текстовой кнопки при наведении. |
textTextActiveColor | Цвет текста текстовой кнопки при нажатии. |
paddingInline | Горизонтальный отступ обычного размера. |
paddingInlineLG | Горизонтальный отступ большого размера. |
paddingInlineSM | Горизонтальный отступ малого размера. |
onlyIconSize | Размер иконки в кнопке без подписи. |
onlyIconSizeLG | Размер иконки в большой кнопке без подписи. |
onlyIconSizeSM | Размер иконки в малой кнопке без подписи. |
linkHoverBg | Фон link при наведении. |
textHoverBg | Фон text при наведении. |
contentFontSize | Размер шрифта обычной кнопки. |
contentFontSizeLG | Размер шрифта большой кнопки. |
contentFontSizeSM | Размер шрифта малой кнопки. |
defaultBgDisabled | Фон недоступной обычной кнопки. |
dashedBgDisabled | Фон недоступной пунктирной кнопки. |
Общие токены текущей темы
Значения ниже получены через публичный theme.useToken().
Переключайте цвет, тёмную тему и компактность в панели страницы — таблица обновится вместе с ними.
| Токен | Назначение | Текущее значение |
|---|---|---|
controlHeight | Высота обычной кнопки, px. | 32 |
controlHeightLG | Высота большой кнопки, px. | 40 |
controlHeightSM | Высота малой кнопки, px. | 24 |
fontSize | Основной размер шрифта, px. | 14 |
fontSizeLG | Большой размер шрифта, px. | 16 |
borderRadius | Базовое скругление, px. | 6 |
colorPrimary | Основной цвет темы. | #2f54eb |
colorBgContainer | Фон контейнера. | #ffffff |
colorBgContainerDisabled | Фон недоступного control. | rgba(0,0,0,0.04) |
colorTextDisabled | Цвет недоступного текста. | rgba(0,0,0,0.25) |
opacityLoading | Непрозрачность при загрузке. | 0.65 |
FAQ
Почему загрузка делает кнопку недоступной?
В текущем @woodger/antd native button получает disabled и aria-busy, когда включается индикатор загрузки. Она перестаёт принимать нажатия и исключается из Tab-порядка. У ссылки с href загрузка отменяет переход. Это особенность поведения нашей реализации; не используйте загрузку как замену проверке права выполнить действие.
Как правильно отключить действие?
Передайте disabled, если действие недоступно. У кнопки с href библиотека блокирует переход и исключает ссылку из Tab-порядка. Цвет и внешний вид сами по себе не запрещают нажатие. Недоступные состояния можно сравнить с обычными кнопками.
Почему основной цвет не меняется через type?
Проверьте, не заданы ли одновременно color и variant, включая настройки ConfigProvider.button. Для нестандартного оформления используйте явную пару свойств и пример цвета и варианта. Токены отдельной кнопки и общая палитра темы решают разные задачи.
Как убрать интервал между двумя китайскими иероглифами?
Задайте autoInsertSpace={false} у Button или в ConfigProvider.button. Эта настройка относится к автоматическому интервалу в короткой китайской подписи; пробелы внутри вашего текста она не удаляет.
Как отключить или заменить волну при нажатии?
Передайте wave={{ disabled: true }} в ConfigProvider. Свой эффект задаётся через wave.showEffect; анимации и созданные DOM-узлы освобождает владелец callback. Пример своей волны показывает оба варианта и учитывает reduced motion.
Кнопки ниже позволяют сравнить эквивалентные type и color + variant, а также нажатие без волны.