Combobox.tsx 1 KB
import { useId } from 'react';
import { cn } from '@/lib/utils';

interface Props {
  value: string;
  onChange: (v: string) => void;
  options: string[];
  placeholder?: string;
  className?: string;
}

/**
 * 带预设候选项的输入(基于原生 datalist):既可用下拉选择,也可自由手填。
 * 满足"尽量提供备选项、也支持手动输入"的需求。
 */
export function Combobox({ value, onChange, options, placeholder, className }: Props) {
  const listId = useId();
  return (
    <>
      <input
        list={listId}
        value={value}
        placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)}
        className={cn(
          'h-9 w-full rounded-lg border border-border bg-background px-3 text-[13px] text-foreground outline-none transition-colors focus:border-primary/50',
          className,
        )}
      />
      <datalist id={listId}>
        {options.map((o) => (
          <option key={o} value={o} />
        ))}
      </datalist>
    </>
  );
}