Svelte
和
shadcn-svelte
UI 组件库创建一个搜索组件,当用户键入
data
数组中确实存在的文本时,我将在搜索输入下方显示一个下拉列表,否则应隐藏下拉列表。
<script lang="ts">
import { Input } from '$lib/components/ui/input';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
let searchValue = '';
let filteredResults: string[] = [];
let isDropdownOpen = false;
const data = [
'California',
'North Carolina',
'North Dakota',
'South Carolina',
'South Dakota',
'Michigan',
'Tennessee',
'Nevada',
'New Hampshire',
'New Jersey'
];
function handleInput() {
filteredResults = data.filter((item) =>
item.toLowerCase().includes(searchValue.toLowerCase())
);
isDropdownOpen = (filteredResults.length > 0 && searchValue !== '');
}
function handleItemSelection(item: string) {
console.log(`${item} selected`);
}
</script>
<Input bind:value={searchValue} on:input={handleInput} placeholder="Search..." />
<DropdownMenu.Root open={isDropdownOpen} disableFocusFirstItem={true}>
<DropdownMenu.Trigger asChild let:builder>
<Button builders={[builder]} class="h-0 m-0 p-0" variant="outline"></Button>
</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Group>
{#each filteredResults as item}
<DropdownMenu.Item on:click={() => handleItemSelection(item)}>{item}</DropdownMenu.Item>
{/each}
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
我的问题是,一旦我开始打字,下拉菜单就会显示,但是焦点将转移到下拉菜单,这将阻止我打字。
<Popover/>
组件遇到的类似问题。解决方案是在
onOpenAutoFocus={(e) => e.preventDefault()}
上使用
<PopoverContent/>
。看起来 无法访问
onOpenAutoFocus
属性,但如果您的内容可以在
<Popover/>
中工作,这可能是一个替代解决方案。
<FormField
control={form.control}
name="search"
render={({ field }) => (
<FormItem className="basis-2/3 grow">
<FormControl>
<>
<Popover open={!!field.value}>
<PopoverTrigger asChild>
<SearchInput
{...field}
type="search"
id="menubar-record-search"
placeholder="Search records..."
/>
</PopoverTrigger>
<PopoverContent onOpenAutoFocus={(e) => e.preventDefault()}>
Place content for the popover here.
</PopoverContent>
</Popover>
</>
</FormControl>
</FormItem>
)}
/>