Transfer
Selecionando entradas por meio da transferência entre duas listas gerenciadas.
Quando usar
Transferência Seleciona um conjunto de participantes, permissões ou tarefas movendo-se entre duas listas. O usuário primeiro marca os registros e depois os transfere com um botão. As duas listas deixam espaço para pesquisa, descrições e comparação das entradas disponíveis e já selecionadas. Para um campo compacto marcado, use Select.
Nesta página, listas amplas percorrem os cartões. As assinaturas de cabeçalho e ação devem explicar o significado da transferência, como "Comando → disponível".
CSS Transferir prefixos Mostrar total ConfigProvider.prefixCls e local prefixCls sem status de reset. Os painéis de transferência usam um prefixo local e Checkbox, Input, Button e Pagination — General Independente. Pesquisa, marcas e entradas migradas são salvas.
Resultado e seleção
targetKeys Contém o resultado da seleção. selectedKeys Contém linhas marcadas temporariamente em ambos os lados. A marca da caixa de seleção em si ainda não adiciona uma entrada ao resultado.
| Tarefa | Configuração | Exemplo |
|---|---|---|
| Aceitar transferência para o modelo | targetKeys, onChange |
Transferência entre listas |
| Gerenciar alocação de tempo | selectedKeys, onSelectChange |
Lista de bases |
| Remover o botão Voltar | oneWay |
Único |
| Armazenar o resultado em Form | form.setFieldValue |
Selecione os participantes no formulário |
O resultado é sempre controlado pelo aplicativo: passe targetKeys e atribua um novo array a onChange. O manipulador também recebe direction e moveKeys — a direção da ação e as teclas das entradas transferidas. Sem atribuição targetKeys O lado direito não mudará. Separe defaultTargetKeys ou bind:targetKeys não.
A seleção pode ser deixada local ou controlada via selectedKeys. onSelectChange Relata duas matrizes: Marcas de lista de origem e destino. O exemplo gerenciado combina-os em um selectedKeys. Limpar a seleção não apaga o resultado e o resultado externo reset não substitui o estado de marca individual.
em oneWay As entradas selecionadas são retornadas por meio do botão Exclusão à direita. Ele exclui a chave de targetKeys mantendo a entrada em dataSource. disabled Bloqueia totalmente a transferência ou para uma entrada separada.
Dados, pesquisas e páginas
Cada entrada precisa de um key único estável. Se o identificador for nomeado de forma diferente, passe rowKey. Exemplo do participante Usa numérica id sem converter um modelo em uma string. Não use a posição na matriz como um identificador ao classificar e atualizar os dados.
render é uma função de gravação normal. Ele retorna texto, Svelte trecho ou objeto com label e texto value. Em tal objeto, value descreve o elemento exibido e não o substitui key. Snippet recebe uma entrada com um argumento; Um exemplo de participantes mostra o nome e a função.
showSearch Adiciona uma pesquisa separada para cada lado. O objeto de configuração define placeholder e start defaultValue; Relatórios de solicitação subsequentes onSearch(direction, value). filterOption Decide quais registros locais serão exibidos. Exemplo de pesquisa Corresponde ao título e à descrição ao mesmo tempo.
Pagination quebra listas locais em páginas; pageSize Especifica seu tamanho. página por Economiza marcas ao trocar de página. Consultas remotas, números de página do servidor e processamento de resposta permanecem no aplicativo. Salve em dataSource Registros de chaves já selecionadas para que a lista de destinos possa exibir suas assinaturas.
Listas e formulários próprios
Para sua interface, você pode conectar Transfer.Search, Transfer.List e Transfer.Operation. Em Exemplo de componentes individuais o aplicativo armazena os resultados de pesquisa de texto, marcas e hifenização.
children Demora Svelte trecho com TransferListBodyProps: filteredItems, selectedKeys, disabled, onItemSelect e onItemSelectAll. Table Transfer Links selectedRowKeys/onSelectionChange tabelas para esses manipuladores. Tree Transfer Conecta a caixa de seleção independente da árvore. Considere disabled e passe as chaves de string reais, não toda a matriz de origem.
embutido pagination em children Não funciona. As páginas e a navegação do seu próprio corpo organizam o aplicativo. onItemSelectAll(keys, 'replace') é fornecido para substituição de marcas em grupo.
Suas ações obter TransferActionInfo. Passe info.disabled e info.onClick ao seu botão; info.icon já considera a direção da interface. footer também aceita trecho. Essas funções não são substituídas por elementos do React ou cloneElement.
classNames e styles Suporta slots compartilhados e individuais source/target; styles Aceita strings e objetos CSS. ConfigProvider.transfer Herda o design e selectionsIcon. Componente Tokens de design (design tokens) theme.components.Transfer Aplicar a listas; As configurações locais são mostradas em Exemplo semântico e Seção de token.
No formulário, o resultado é armazenado em form.values e onChange causas form.setFieldValue. Regra required Verifica o conjunto de destino. Reset Form Restaura initialValues e limpa separadamente selectedKeys. Caixa de seleção e botões nativos estão disponíveis no teclado; bind:nativeElement Retorna a raiz div, métodos individuais focus/blur transferência não.
Exemplos
Transferência entre listas
A seleção de linhas e chaves transferidas são estados diferentes. targetKeys é sempre controlado pelo aplicativo; onChange Relata a direção e as chaves transportadas.
<script lang="ts">
import { Transfer, type TransferDirection, type TransferKey } from '@woodger/antd';
const dataSource = Array.from({ length: 8 }, (_, index) => ({
key: String(index + 1),
title: `Item ${index + 1}`,
description: `Descrição ${index + 1}`,
disabled: index === 3
}));
let targetKeys = $state<TransferKey[]>(['2']);
let lastMove = $state(("Sem transferências"));
function handleChange(next: TransferKey[], direction: TransferDirection, moved: TransferKey[]) {
targetKeys = next;
lastMove = ("" + String((direction)) + ": " + String((moved.join(', '))) + "");
}
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
output { overflow-wrap: anywhere; }
</style>
<div
class="lists"
role="region"
aria-label={("Listas: Transferência entre listas")}
tabindex="0"
>
<Transfer dataSource={(dataSource)} {targetKeys} titles={([
"Disponível",
"Selecionado"
])} actions={(["Adicionar", "Retorno"])}
render={item => item.title} onChange={handleChange} />
</div>
<p><output aria-label={("Resultado da transferência")}>{(targetKeys.join(', ')
|| ("Vazio"))}; {lastMove}</output></p>
- Item 2
- Item 3
Único
oneWay Deixa um botão de transferência. Na lista da direita, os elementos são removidos por botões separados.
<script lang="ts">
import { Transfer, type TransferKey } from '@woodger/antd';
const dataSource = Array.from({ length: 8 }, (_, index) => ({
key: String(index + 1),
title: `Item ${index + 1}`,
description: `Descrição ${index + 1}`,
disabled: index === 3
}));
let targetKeys = $state<TransferKey[]>(['2', '3']);
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
output { overflow-wrap: anywhere; }
</style>
<div class="lists" role="region" aria-label={("Listas: One Way")} tabindex="0">
<Transfer dataSource={(dataSource)} {targetKeys} oneWay actions={([
"Adicionar"
])} titles={(["Disponível", "Selecionado"])}
render={item => item.title} onChange={next => { targetKeys = next; }} />
</div>
<p><output aria-label={("Seleção unidirecional")}>{targetKeys.join(', ')}</output></p>
Pesquisa independente
Cada lista armazena sua solicitação. filterOption Pesquisas por nome e descrição; onSearch Comunica o lado e a string.
<script lang="ts">
import { Transfer, type TransferKey } from '@woodger/antd';
const dataSource = Array.from({ length: 8 }, (_, index) => ({
key: String(index + 1),
title: `Item ${index + 1}`,
description: `Descrição ${index + 1}`,
disabled: index === 3
}));
let targetKeys = $state<TransferKey[]>(['2', '5']);
let query = $state('');
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
output { overflow-wrap: anywhere; }
</style>
<div
class="lists"
role="region"
aria-label={("Listas: Pesquisa independente")}
tabindex="0"
>
<Transfer
dataSource={(dataSource)}
{targetKeys}
showSearch={{ placeholder: "Título ou descrição" }}
titles={(["Disponível", "Selecionado"])}
actions={(["Adicionar", "Retorno"])}
render={item => item.title}
filterOption={(search, item) => `${item.title} ${item.description}`.toLowerCase().includes(
search.toLowerCase()
)}
onSearch={(direction, search) => { query = ("" + String((direction)) + ": " + String((search)) + ""); }}
onChange={next => { targetKeys = next; }}
/>
</div>
<p><output
aria-label={("Transferência de pesquisa")}
>{(query || ("Pesquisa não especificada"))}</output></p>
Lista de bases
footer Obtém os parâmetros da lista e direction. O botão remove a seleção em seu lado; Geral disabled Bloqueia ações.
<script lang="ts">
import {
Button,
Transfer,
type TransferDirection,
type TransferKey,
type TransferListProps
} from '@woodger/antd';
const dataSource = Array.from({ length: 8 }, (_, index) => ({
key: String(index + 1),
title: `Item ${index + 1}`,
description: `Descrição ${index + 1}`,
disabled: index === 3
}));
let targetKeys = $state<TransferKey[]>(['2']);
let disabled = $state(false);
type Row = typeof dataSource[number];
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
.footer { padding: 8px 12px; }
</style>
<p>
<label><input type="checkbox" bind:checked={disabled} />{(" Bloqueie ambas as listas")}</label>
</p>
{#snippet footer(list: TransferListProps<Row>, info: { direction: TransferDirection })}
<div class="footer"><Button
size="small"
disabled={list.disabled}
onclick={() => list.onItemSelectAll(list.checkedKeys, false)}
>{("Desmarque ")}{(info.direction)}</Button></div>
{/snippet}
<div class="lists" role="region" aria-label={("Listas de tabelas: Lista do porão")} tabindex="0">
<Transfer
dataSource={(dataSource)}
{targetKeys}
{disabled}
{footer}
titles={(["Disponível", "Selecionado"])}
render={item => item.title}
actions={(["Adicionar", "Retorno"])}
onChange={next => { targetKeys = next; }}
/>
</div>
Seus dados e assinaturas
rowKey lê numérico id. render Retorna label Snippet e value para metadados de texto; As chaves permanecem números.
<script lang="ts">
import { Transfer, type TransferKey } from '@woodger/antd';
interface Person { id: number; name: string; role: string; }
const dataSource: Person[] = [
{ id: 10, name: "Anna", role: "Desenvolvimento" },
{ id: 20, name: "Boris", role: "Documentação" }
];
let targetKeys = $state<TransferKey[]>([]);
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
output { overflow-wrap: anywhere; }
</style>
{#snippet label(person: Person)}
<strong>
{person.name}
</strong>
<small>
{(person.role)}
</small>
{/snippet}
<div
class="lists"
role="region"
aria-label={("Listas: Seus dados e assinaturas")}
tabindex="0"
>
<Transfer
dataSource={(dataSource)}
{targetKeys}
rowKey={person => person.id}
titles={(["Membros", "Comando"])}
actions={(["para comandar", "Retorno"])}
render={person => ({ label, value: person.name })}
onChange={next => { targetKeys = next; }}
/>
</div>
<p><output aria-label={("Chaves do Participante")}>{JSON.stringify(targetKeys)}</output></p>
Seus botões de transferência
A ação do trecho obtém disabled, direction, icon e onClick. Passe-os para o seu Button, mantendo uma transferência regular.
<script lang="ts">
import { Button, Transfer, type TransferActionInfo, type TransferKey } from '@woodger/antd';
const dataSource = Array.from({ length: 8 }, (_, index) => ({
key: String(index + 1),
title: `Item ${index + 1}`,
description: `Descrição ${index + 1}`,
disabled: index === 3
}));
let targetKeys = $state<TransferKey[]>([]);
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
output { overflow-wrap: anywhere; }
</style>
{#snippet action(info: TransferActionInfo)}
<Button
size="small"
disabled={info.disabled}
onclick={info.onClick}
aria-label={(info.direction === 'right' ? "Enviar direito" : "Retornar à esquerda")}
>{@render info.icon()}</Button>
{/snippet}
<div
class="lists"
role="region"
aria-label={("Listas: Seus botões de transferência")}
tabindex="0"
>
<Transfer dataSource={(dataSource)} {targetKeys} actions={([
action,
action
])} titles={(["Disponível", "Selecionado"])}
render={item => item.title} onChange={next => { targetKeys = next; }} />
</div>
<p><output aria-label={("Seleção com suas ações")}>{(targetKeys.join(', ')
|| ("Vazio"))}</output></p>
Componentes de transferência individuais
Transfer.Search Filtra os registros disponíveis, Transfer.List Mostra a eles e Transfer.Operation Transfere os elementos marcados. O aplicativo armazena os dois conjuntos de chaves.
<script lang="ts">
import { Transfer, type TransferKey } from '@woodger/antd';
const items = ['Button', 'Input', 'Select', 'Tabs'].map(title => ({ key: title, title }));
const border = '1px solid var(--ant-color-border, #d9d9d9)';
let query = $state('');
let checkedKeys = $state<TransferKey[]>([]);
let targetKeys = $state<TransferKey[]>([]);
const available = $derived(items.filter(item =>
!targetKeys.includes(item.key) && item.title.toLowerCase().includes(query.trim().toLowerCase())
));
function handleFilter(event: Event & { currentTarget: HTMLInputElement }) {
query = event.currentTarget.value;
}
function handleClear() {
query = '';
}
function selectItem(key: TransferKey, selected: boolean) {
checkedKeys = selected
? [...checkedKeys, key]
: checkedKeys.filter(checked => checked !== key);
}
function move() {
targetKeys = [...targetKeys, ...checkedKeys];
checkedKeys = [];
}
</script>
<div class="example">
<Transfer.Search
aria-label={("Localizar componente")}
placeholder={("Localizar componente")}
value={query}
onChange={handleFilter}
{handleClear}
/>
<Transfer.List
prefixCls="available"
direction="left"
dataSource={available}
{checkedKeys}
titleText={("Disponível")}
notFoundContent={("Sem dados")}
showSelectAll={false}
classNames={{}}
styles={{
section: {
border,
borderRadius: '8px',
minHeight: '172px'
},
header: {
display: 'flex',
flexDirection: 'row-reverse',
justifyContent: 'space-between',
padding: '8px 12px',
borderBottom: border
},
list: {
margin: 0,
padding: 0,
listStyle: 'none'
},
item: {
display: 'flex',
alignItems: 'center',
gap: '8px',
padding: '6px 12px'
}
}}
{handleFilter}
{handleClear}
onItemSelect={selectItem}
onItemSelectAll={() => {}}
onScroll={() => {}}
render={item => item.title}
/>
<Transfer.Operation
oneWay
actions={[("Adicionar")]}
rightActive={checkedKeys.length > 0}
moveToRight={move}
/>
<p><output aria-label={("Selecionado")}>{targetKeys.join(', ') || ("Vazio")}</output></p>
</div>
<style>
.example {
display: grid;
gap: 12px;
}
p {
margin: 0;
}
</style>
Listas de páginas
pagination Limita as linhas visíveis de cada lado. Pesquisar e virar Salvar as teclas selecionadas.
<script lang="ts">
import { Transfer, type TransferKey } from '@woodger/antd';
const dataSource = Array.from({ length: 8 }, (_, index) => ({
key: String(index + 1),
title: `Item ${index + 1}`,
description: `Descrição ${index + 1}`,
disabled: index === 3
}));
let targetKeys = $state<TransferKey[]>([]);
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
output { overflow-wrap: anywhere; }
</style>
<div
class="lists"
role="region"
aria-label={("Listas: Listas de páginas")}
tabindex="0"
>
<Transfer dataSource={(dataSource)} {targetKeys} pagination={({
pageSize: 3,
simple: false,
showSizeChanger: true
})}
titles={(["Disponível", "Selecionado"])} actions={([
"Adicionar",
"Retorno"
])} render={item => item.title}
onChange={next => { targetKeys = next; }} />
</div>
<p><output aria-label={("Seleção de páginas")}>{(targetKeys.join(', ')
|| ("Vazio"))}</output></p>
Título | Descrição | |
|---|---|---|
| Item 1 | Descrição 1 | |
| Item 2 | Descrição 2 | |
| Item 3 | Descrição 3 | |
| Item 4 | Descrição 4 | |
| Item 5 | Descrição 5 | |
| Item 6 | Descrição 6 | |
| Item 7 | Descrição 7 | |
| Item 8 | Descrição 8 |
Título | Descrição | |
|---|---|---|
Sem dados | ||
Transferência com tabelas
children Substitui o corpo da lista por público Table. selectedRowKeys e onSelectionChange estão relacionados a onItemSelectAll; pagination A transferência em children não funciona.
<script lang="ts">
import {
Table,
Transfer,
type TableColumn,
type TransferKey,
type TransferListBodyProps
} from '@woodger/antd';
const dataSource = Array.from({ length: 8 }, (_, index) => ({
key: String(index + 1),
title: `Item ${index + 1}`,
description: `Descrição ${index + 1}`,
disabled: index === 3
}));
interface Row { key: string; title: string; description: string; disabled: boolean; }
const columns: TableColumn<Row>[] = [
{ key: 'title', title: "Título", dataIndex: 'title' },
{ key: 'description', title: "Descrição", dataIndex: 'description' }
];
let targetKeys = $state<TransferKey[]>([]);
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
output { overflow-wrap: anywhere; }
</style>
<div
class="lists"
role="region"
aria-label={("Listas: Transferir com")}
tabindex="0"
>
<Transfer dataSource={(dataSource)} {targetKeys} titles={([
"Disponível",
"Selecionado"
])} showSelectAll={false}
styles={{ section: `
width: 360px;
height: 300px;
` }} actions={([
"Adicionar",
"Retorno"
])}
onChange={next => { targetKeys = next; }}>
{#snippet children(list: TransferListBodyProps<Row>)}
<Table
dataSource={(list.filteredItems)}
columns={(columns)}
rowKey="key"
pagination={(false)}
selectedRowKeys={list.selectedKeys.map(String)}
disabled={list.disabled}
rowSelection={{
getCheckboxProps: row => ({
disabled: row.disabled,
'aria-label': row.title
})
}}
onSelectionChange={keys => list.onItemSelectAll(keys, 'replace')}
/>
{/snippet}
</Transfer>
</div>
<p><output aria-label={("Seleção tabular")}>{(targetKeys.join(', ')
|| ("Vazio"))}</output></p>
Selecione os itens no diretório
Transferência com árvore
A fonte mostra uma árvore de grupo com caixa de seleção independente. O alvo usa Checkbox; Ambos os corpos estão conectados à transferência pública de retorno de chamada.
<script lang="ts">
import {
Checkbox,
Transfer,
Tree,
type TransferKey,
type TransferListBodyProps,
type TreeDataNode
} from '@woodger/antd';
const dataSource = Array.from({ length: 8 }, (_, index) => ({
key: String(index + 1),
title: `Item ${index + 1}`,
description: `Descrição ${index + 1}`,
disabled: index === 3
}));
interface Row { key: string; title: string; description: string; disabled: boolean; }
let targetKeys = $state<TransferKey[]>([]);
function asTree(records: readonly Row[]): TreeDataNode[] {
return [{ key: 'group', title: "Catálogo", checkable: false, selectable: false,
children: records.map(row => ({ key: row.key, title: row.title, disabled: row.disabled }))
}];
}
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
output { overflow-wrap: anywhere; }
.target {
display: grid;
gap: 12px;
padding: 12px;
}
</style>
<div
class="lists"
role="region"
aria-label={("Listas: Transferir com árvore")}
tabindex="0"
>
<Transfer dataSource={(dataSource)} {targetKeys} titles={([
"Catálogo",
"Selecionado"
])} showSelectAll={false}
styles={{ section: `
width: 260px;
height: 280px;
` }} actions={([
"Adicionar",
"Retorno"
])}
onChange={next => { targetKeys = next; }}>
{#snippet children(list: TransferListBodyProps<Row>)}
{#if list.direction === 'left'}
<Tree aria-label={("Árvore de itens disponíveis")} treeData={asTree(
list.filteredItems
)} checkable checkStrictly
defaultExpandAll checkedKeys={list.selectedKeys.map(String)} disabled={list.disabled}
onCheck={(_keys, info) => list.onItemSelect(info.node.key, info.checked)} />
{:else}
<div class="target">
{#each list.filteredItems as row (row.key)}
<Checkbox checked={list.selectedKeys.includes(row.key)} disabled={list.disabled
|| row.disabled}
onChange={event => list.onItemSelect(row.key, event.target.checked)}>{(row.title)}</Checkbox>
{:else}<p>{("Selecione os itens no diretório")}</p>{/each}
</div>
{/if}
{/snippet}
</Transfer>
</div>
<p><output aria-label={("Seleção da Madeira")}>{(targetKeys.join(', ')
|| ("Vazio"))}</output></p>
Status de validação
status Conjuntos error ou warning. O status herdado FormItem também é compatível.
<script lang="ts">
import { Transfer, type TransferKey } from '@woodger/antd';
const dataSource = Array.from({ length: 8 }, (_, index) => ({
key: String(index + 1),
title: `Item ${index + 1}`,
description: `Descrição ${index + 1}`,
disabled: index === 3
}));
let targetKeys = $state<TransferKey[]>(['2']);
let warning = $state(true);
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
</style>
<div
class="lists"
role="region"
aria-label={("Listas: Verifique o status")}
tabindex="0"
>
<Transfer dataSource={(dataSource)} {targetKeys} status="error" titles={(["Erro", "Selecionado"])}
render={item => item.title} onChange={next => { targetKeys = next; }} />
</div>
<p><label><input
type="checkbox"
bind:checked={warning}
/>{(" Mostrar aviso")}</label></p>
<div
class="lists"
role="region"
aria-label={("Listas: Verifique o status")}
tabindex="0"
>
<Transfer
dataSource={(dataSource)}
{targetKeys}
status={warning ? 'warning' : ''}
titles={(["Verifique", "Selecionado"])}
render={item => item.title}
onChange={next => { targetKeys = next; }}
/>
</div>
Semantic slots
styles e classNames Suporta slots comuns e source/target individuais. A função obtém info.props.
<script lang="ts">
import { Transfer, type TransferKey } from '@woodger/antd';
const dataSource = Array.from({ length: 8 }, (_, index) => ({
key: String(index + 1),
title: `Item ${index + 1}`,
description: `Descrição ${index + 1}`,
disabled: index === 3
}));
let targetKeys = $state<TransferKey[]>(['2']);
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
</style>
<div class="lists" role="region" aria-label={("Listas: Slots semânticos")} tabindex="0">
<Transfer dataSource={(dataSource)} {targetKeys} titles={([
"Fonte",
"Atribuir"
])} actions={(["Adicionar", "Retorno"])}
render={item => item.title} classNames={{ title: 'documented-transfer-title' }}
styles={({ props }) => ({
section: 'border-style:dashed',
itemContent: 'font-weight:600',
source: { header: 'background:var(--ant-color-fill-secondary)' },
target: { header: props.disabled ? '' : 'background:var(--ant-color-primary-bg)' }
})} onChange={next => { targetKeys = next; }} />
</div>
Transferência bloqueada
disabled Alocação e ação de blocos; A string inacessível não é portada com as disponíveis.
<script lang="ts">
import { Transfer, type TransferKey } from '@woodger/antd';
const dataSource = Array.from({ length: 8 }, (_, index) => ({
key: String(index + 1),
title: `Item ${index + 1}`,
description: `Descrição ${index + 1}`,
disabled: index === 3
}));
let targetKeys = $state<TransferKey[]>(['2']);
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
</style>
<div
class="lists"
role="region"
aria-label={("Listas: Transferência bloqueada")}
tabindex="0"
>
<Transfer dataSource={(dataSource)} {targetKeys} disabled titles={([
"Disponível",
"Selecionado"
])}
render={item => item.title} onChange={next => { targetKeys = next; }} />
</div>
Selecione os participantes no formulário
Form Armazene targetKeys Explicitamente. submit Verifica a seleção não vazia, reset Restaura as teclas de início e remove a seleção.
<script lang="ts">
import { Button, Form, FormItem, Transfer, createForm, type TransferKey } from '@woodger/antd';
const dataSource = Array.from({ length: 8 }, (_, index) => ({
key: String(index + 1),
title: `Item ${index + 1}`,
description: `Descrição ${index + 1}`,
disabled: index === 3
}));
const form = createForm<{ members: string[] }>({
initialValues: { members: ['2'] },
rules: ({ members: [{ required: true, message: "Selecionar membros." }] })
});
let selectedKeys = $state<TransferKey[]>([]);
let result = $state('');
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
.lists:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
output { overflow-wrap: anywhere; }
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
</style>
<Form {form} onFinish={values => { result = values.members.join(', '); }}>
<FormItem hasFeedback name="members" label={("Alinhamento")}>
<div
class="lists"
role="region"
aria-label={("Listas: Selecionando participantes no formulário")}
tabindex="0"
>
<Transfer
dataSource={(dataSource)}
targetKeys={form.values.members}
{selectedKeys}
titles={(["Disponível", "Comando"])}
actions={(["Adicionar", "Retorno"])}
render={item => item.title}
onChange={next => form.setFieldValue('members', next.map(String))}
onSelectChange={(left, right) => { selectedKeys = [...left, ...right]; }}
/>
</div>
</FormItem>
<div
class="actions"
><Button
type="primary"
htmlType="submit"
>{("Salvar comando")}</Button><Button
htmlType="reset"
onclick={() => { selectedKeys = []; }}
>{("Reiniciar comando")}</Button></div>
</Form>
<p><output aria-label={("Comando salvo")}>{(result
|| ("Não enviado"))}</output></p>
- /2
- /1
Tarefas para trabalhar
Exemplo original da revisão: seleção gerenciada, pesquisa, páginas, oneWay e redefinir duas listas.
<script lang="ts">
import { Button, Transfer, type TransferKey } from '@woodger/antd';
const dataSource = Array.from({ length: 12 }, (_, index) => ({
key: String(index + 1),
title: `Tarefa ${index + 1}`,
description: `Descrição da tarefa ${index + 1}`,
disabled: index === 3
}));
let targetKeys = $state<TransferKey[]>(['2', '5']);
let selectedKeys = $state<TransferKey[]>([]);
let oneWay = $state(false);
</script>
<style>
.controls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 16px;
}
.controls label {
display: flex;
align-items: center;
gap: 8px;
}
.lists {
max-width: 100%;
overflow-x: auto;
}
output {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
</style>
<div class="controls">
<label><input
type="checkbox"
bind:checked={oneWay}
/>{(" Apenas uma maneira")}</label>
<Button onclick={() => {
targetKeys = ['2', '5'];
selectedKeys = [];
}}>{("Redefinir listas")}</Button>
</div>
<div class="lists">
<Transfer
dataSource={(dataSource)}
{targetKeys}
{selectedKeys}
{oneWay}
titles={(["Disponível", "Selecionado"])}
actions={["Selecione Tarefas", "Tarefas de retorno"]}
showSearch={{ placeholder: "Localizar tarefa" }}
render={item => item.title}
pagination={({ pageSize: 5 })}
styles={{ section: `
width: 240px;
height: 300px;
` }}
onChange={next => { targetKeys = next; }}
onSelectChange={(source, target) => { selectedKeys = [...source, ...target]; }}
/>
</div>
<output aria-label={("Tarefas transferidas")}>{targetKeys.length ? targetKeys.map(
key => `Tarefa ${key}`
).join(', ') : ("Nenhuma tarefa selecionada")}</output>
Os painéis de transferência usam o prefixo local, enquanto a caixa de seleção, entrada, botão e paginação são compartilhados independentes. Pesquisa, marcas e entradas migradas são salvas.
CSS Transferir prefixos
namespace geral ConfigProvider e local prefixCls; O estado do componente é salvo ao alterar o nome.
<script lang="ts">
import { Checkbox, ConfigProvider, Transfer, type TransferKey } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-transfer' : '');
let targetKeys = $state<TransferKey[]>(['docs']);
const dataSource = [
{ key: 'docs', title: "Documentação" },
{ key: 'examples', title: "Exemplos" }
];
</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; }
.transfer-scroll {
min-width: 0;
max-width: 100%;
overflow-x: auto;
}
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("General Prefix Transfer Suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Transferência de prefixo local")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'transfer-theme' } }}>
<div class="prefix-stage">
<div class="transfer-scroll">
<Transfer
prefixCls={localPrefix}
dataSource={(dataSource)}
{targetKeys}
showSearch
render={item => item.title}
titles={(["Disponível", "Selecionado"])}
onChange={keys => targetKeys = keys}
/>
</div>
<output aria-label={("Selecionar transferência com")}>{(targetKeys.join(', ')
|| '—')}</output>
</div>
</ConfigProvider>
<output
aria-label={("prefixo CSS-transferência de prefixo")}
>{("Geral: ")}{prefix}{("; Local: ")}{(localPrefix
|| ("Do provedor"))}</output>
<p>
{("Os painéis de transferência usam o prefixo local, enquanto a caixa de seleção, entrada, botão e paginação são compartilhados independentes. Pesquisa, marcas e entradas migradas são salvas.")}
</p>
</div>
API
Onze temas de página ao vivo no Ant.Design são apresentados nos cartões acima: transferência básica e unidirecional, busca, porão, seus dados e ações, páginas, Table/Tree, status e semântica slots. Além disso, disabled, Form e as tarefas da revisão são mostradas.
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
prefixCls | Complete CSS prefixo do componente e suas partes. O suporte local não vazio é prioridade; String vazia e undefined Herdar ConfigProvider. O namespace do tópico é definido separadamente. | string | ConfigProvider.prefixCls + "-transfer" |
dataSource | Todas as entradas de ambos os lados, incluindo as já selecionadas. As chaves devem ser exclusivas. | readonly RecordType[] | [] |
targetKeys | Resultado gerenciado. Pegue onChange; Local defaultTargetKeys e bind:targetKeys não. | readonly TransferKey[] | [] |
selectedKeys | Alocação temporária de ambos os lados. Com onSelectChange você pode controlá-lo explicitamente. | readonly TransferKey[] | Seleção local |
rowKey | Chave de registro. TransferKey Salva string, number ou bigint. | (record) => TransferKey | record.key |
render | String, Svelte trecho com entrada ou objeto. value Define os metadados do texto, label — conteúdo. | (record) => content | { label, value } | — |
onChange | Novo resultado, direção de transferência e teclas de entradas em movimento. | (targetKeys, direction, moveKeys) => void | — |
onSelectChange | Divide a alocação temporária das listas de origem e destino. | (sourceSelectedKeys, targetSelectedKeys) => void | — |
showSearch | Linhas de busca independentes por lados. defaultValue é lido ao criar uma lista. | boolean | { placeholder, defaultValue } | false |
filterOption | seu filtro. onSearch Comunica o lado físico e a string de pesquisa. | (search, record, direction) => boolean | por texto Render |
oneWay | Um botão de transferência; No lado alvo, aparecem os botões de exclusão dos selecionados. | boolean | false |
actions | Strings para botões padrão ou trechos com onClick, disabled, direction e icon. | readonly TransferAction[] | setas |
pagination | pageSize, simples, showSizeChanger e showLessItems. Se children não se aplica. | boolean | TransferPagination | false |
footer | Seu porão com o contexto da lista e suas ações. | Snippet<[TransferListProps, { direction }]> | — |
children | Substitui o corpo de ambos os lados. O aplicativo conecta seus controles com onItemSelect/onItemSelectAll. | Snippet<[TransferListBodyProps<RecordType>]> | Lista padrão |
titles | Títulos de duas listas. locale Também altera a pesquisa, os contadores e os comandos. | readonly TransferContent[] | da localidade |
showSelectAll | Mostra a seleção geral. selectAllLabels Substitui as assinaturas do contador. | boolean | true |
disabled | Bloqueia todas as ações. A entrada disabled é bloqueada separadamente. | boolean | do formulário / ConfigProvider |
status | error ou warning para verificação. Uma string vazia herda o status de um campo. | TransferStatus | de FormItem |
styles | Strings e objetos CSS para peças comuns e listas individuais source e target. classNames Adota a mesma estrutura de classe. | TransferSemanticValue<CSSStyle> | — |
nativeElement | bind:nativeElement Retorna a raiz. Separar focus()/blur() não são exportados. | HTMLDivElement | — |
As definições completas de propriedades pertencem ao pacote. ReactNode e cloneElement em Svelte substituído por trechos com manipuladores explicitamente transmitidos. Semântica styles conter CSS strings; styles.section Faz as duas colunas.
Seu corpo da lista
children obtém TransferListBodyProps: filteredItems, selectedKeys, disabled, direction, onItemSelect e onItemSelectAll. direction – lado físico left/right e mudanças no RTL. Os botões General Header, Search e Transferir permanecem com Transfer; O conteúdo do corpo é de propriedade do aplicativo.
Table Transfer Conecta o público selectedRowKeys/onSelectionChange tabela com uma seleção de lista. Em Svelte eles estão na mesa, não dentro do React rowSelection.
Tree Transfer Usa a caixa de seleção independente da árvore e a lista da caixa de seleção à direita. A marca de string causa onItemSelect; A seleção do grupo da tabela é onItemSelectAll(keys, 'replace'). A paginação de transferência nativa em children não funciona: as páginas do próprio corpo organiza o aplicativo.
Semantic DOM
Em um corpo normal, as strings usam a caixa de seleção Native, Actions - Buttons, Search - Input. Listas amplas desta página percorrem a área nomeada disponível no teclado. Para sua composição, salve os nomes disponíveis e os controles disabled.
| Slots | Atribuir |
|---|---|
root / actions | Raiz e área do botão Transferir. |
section / header / title / body | Lista, título, texto e corpo. |
list / item / itemIcon / itemContent / footer | Lista de strings, linha, ícone, conteúdo e porão. |
source / target | Slots de seção aninhada para o lado de origem e destino. Os slots locais se sobrepõem ao comum. |
classNames/styles Pode ser um objeto ou função de info.props. ConfigProvider.transfer Herda class, style, classNames, styles e selectionsIcon. bind:nativeElement Retorna raiz div; Não há métodos de foco separados para a transferência.
Tokens de design
Seis tokens de componentes são verificados com Ant.Design e ComponentTokenMap['Transfer']. theme.components.Transfer Aplica os tamanhos e recuos das listas. Semântica styles e ConfigProvider.transfer Defina configurações locais adicionais.
<script lang="ts">
import { ConfigProvider, Transfer, type TransferKey } from '@woodger/antd';
let targetKeys = $state<TransferKey[]>(['b']);
</script>
<style>
.lists {
max-width: 100%;
overflow-x: auto;
}
</style>
<ConfigProvider transfer={{
styles: {
section: `
width: 220px;
height: 220px;
`,
title: 'font-weight:600',
target: { header: 'background:var(--ant-color-primary-bg)' }
}
}}>
<div
class="lists"
role="region"
aria-label={("Transferência de design do provedor")}
tabindex="0"
>
<Transfer dataSource={([{ key: 'a', title: "Desenvolvimento" }, {
key: 'b',
title: "Documentação"
}])}
{targetKeys} titles={(["Disponível", "Selecionado"])} actions={([
"Adicionar",
"Retorno"
])}
render={item => item.title} onChange={next => { targetKeys = next; }} />
</div>
</ConfigProvider>
| Token | Atribuir |
|---|---|
headerHeight | Altura do cabeçalho da lista. |
itemHeight | Altura mínima da linha. |
itemPaddingBlock | Recuo na linha vertical. |
listHeight | Altura da lista. |
listWidth | Largura regular da lista. |
listWidthLG | Largura da lista estendida. |
Tokens comuns do tema atual
Os valores são lidos de forma reativa por meio de theme.useToken().
| Token | Valor atual |
|---|---|
colorBgContainer | #ffffff |
colorBgContainerDisabled | rgba(0,0,0,0.04) |
colorBorder | #d9d9d9 |
colorError | #ff4d4f |
colorLink | #1677ff |
colorLinkActive | #0958d9 |
colorLinkHover | #69b1ff |
colorPrimaryBorder | #adc6ff |
colorSplit | rgba(5,5,5,0.06) |
colorText | rgba(0,0,0,0.88) |
colorTextDisabled | rgba(0,0,0,0.25) |
colorTextSecondary | rgba(0,0,0,0.65) |
colorWarning | #faad14 |
borderRadiusLG | 8 |
controlHeightLG | 40 |
controlItemBgActive | #f0f5ff |
controlItemBgActiveHover | #d6e4ff |
controlItemBgHover | rgba(0,0,0,0.04) |
fontFamily | -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
'Noto Color Emoji' |
fontSize | 14 |
fontSizeIcon | 12 |
lineHeight | 1.5714285714285714 |
lineType | solid |
lineWidth | 1 |
lineWidthFocus | 3 |
linkDecoration | none |
linkFocusDecoration | none |
linkHoverDecoration | none |
marginXS | 8 |
marginXXS | 4 |
motionDurationSlow | 0.3s |
paddingSM | 12 |
paddingXS | 8 |
FAQ
Por que a linha marcada ainda não está à direita?
Marque a linha, pressione a transferência e aceite o novo targetKeys em onChange. A seleção e o resultado são armazenados separadamente.
O que significa deleção em oneWay?
Exclua a chave do conjunto de destino. A entrada é devolvida à lista original; Os dados no servidor não são excluídos.
Como conectar dados remotos?
Gerencie as páginas de download e servidor no aplicativo. Deixe registros das chaves selecionadas em dataSource para exibir o lado alvo; A pesquisa integrada filtra os dados locais.
Como selecionar uma chave de um campo com um nome diferente?
Pass rowKey, por exemplo, uma função retornando id membro. A chave deve permanecer exclusiva em ambos os lados e ao atualizar a matriz.