Shadcn/ui 範例
使用 Shadcn/ui 元件搭配 Radix UI 基礎元件與 Tailwind CSS 的範例。
基本下拉選單
使用 Radix Select 的簡單國家下拉選單。注意:此元件不支援篩選功能,如需篩選請使用 Combobox。
常用國家置頂
常用國家固定在頂部,並以分隔線區隔。
可搜尋下拉選單
核心功能!輸入英文即可篩選中文國家名稱。試著輸入「united」來找到美國和英國。
排序選項
可切換筆畫順序、英文字母順序或注音順序排序。
Sort by:
國旗開關
切換國旗表情符號的顯示與隱藏。
國家白名單
限制只顯示特定國家(例如:亞洲國家)。
Showing only Asian countries (13 countries)
程式碼範例
import { useCountryList } from 'use-country-list-zh';
import { Command, CommandInput, CommandList, CommandItem } from '@/components/ui/command';
import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover';
function CountryCombobox() {
const [open, setOpen] = useState(false);
const {
countries,
query,
setQuery,
selectedCountry,
setSelectedCountry,
getDisplayText,
} = useCountryList({
showFlag: true,
topList: ['TW', 'US', 'JP'],
});
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button variant="outline">
{selectedCountry ? getDisplayText(selectedCountry) : "Select..."}
</Button>
</PopoverTrigger>
<PopoverContent>
<Command shouldFilter={false}>
<CommandInput
value={query}
onValueChange={setQuery}
placeholder="Type in English..."
/>
<CommandList>
{countries.map((country) => (
<CommandItem
key={country.code}
onSelect={() => {
setSelectedCountry(country);
setOpen(false);
}}
>
{getDisplayText(country)}
</CommandItem>
))}
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}