在 shadcn 组合框上设置默认值

问题描述 投票:0回答:1

我想设置默认值我的表单,使用组合框为我的编辑页面选择城市

这是我的组合框代码

    <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>
reactjs typescript shadcnui
1个回答
0
投票

shadcn/combobox
不提供
defaultValue
属性的支持。但我假设您使用
useState
钩子将选定的城市保留在状态中。最有可能它的定义是这样的:

const [value, setValue] = useState(null);

因此,为了模仿您需要的行为,您只需为

useState
钩子提供初始值即可:

const [value, setValue] = useState(cities[0]?.name);
© www.soinside.com 2019 - 2024. All rights reserved.