我想设置默认值我的表单,使用组合框为我的编辑页面选择城市
这是我的组合框代码
<Command>
<CommandInput placeholder="Search kota..." />
<CommandEmpty>No kota found.</CommandEmpty>
<CommandList>
{cities.map((city) => (
<CommandItem
key={city.id}
value={city.name}
onSelect={() => {
setData((data) => ({
...data,
city: city.id.toString(),
subdistrict: "",
village: "",
}));
fetchSubdistrict(city.id);
setVillages([]);
setValue(city.name);
setOpen(false);
}}
>
{`${city.type} ${city.name}`}
</CommandItem>
))}
</CommandList>
</Command>
shadcn/combobox
不提供defaultValue
属性的支持。但我假设您使用 useState
钩子将选定的城市保留在状态中。最有可能它的定义是这样的:
const [value, setValue] = useState(null);
因此,为了模仿您需要的行为,您只需为
useState
钩子提供初始值即可:
const [value, setValue] = useState(cities[0]?.name);