反应选择和打字稿:类型 'string' 不可分配给类型 'ValueType<OptionTypeBase>'

kur*_*tgn 3 typescript reactjs react-select

我正在尝试创建一个使用 react-select 和 typescript 的示例组件。

为此,我创建了一个功能组件并添加了react-select docs 中的默认示例:

const options = [
    {value: 'chocolate', label: 'Chocolate'},
    {value: 'strawberry', label: 'Strawberry'},
    {value: 'vanilla', label: 'Vanilla'},
];

const MyComponent = () => {

    const [selectedOption, setSelectedOption] = useState('chocolate');

    const handleChange = (option: string) => {
        setSelectedOption(option);
    };

    return (
        <Select
            value={selectedOption}
            onChange={(option) => handleChange(option)}
            options={options}
        />
    );

};
Run Code Online (Sandbox Code Playgroud)

但是,这给了我一个错误:

 Overload 1 of 2, '(props: Readonly<Pick<Props<OptionTypeBase>, string | number> & Props<OptionTypeBase> & Props<OptionTypeBase>>): StateManager<...>', gave the following error.
    Type 'string' is not assignable to type 'ValueType<OptionTypeBase>'.
  Overload 2 of 2, '(props: Pick<Props<OptionTypeBase>, string | number> & Props<OptionTypeBase> & Props<OptionTypeBase>, context?: any): StateManager<...>', gave the following error.
    Type 'string' is not assignable to type 'ValueType<OptionTypeBase>'.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

我的包裹是:

    "@types/react": "^16.9.19",
    "@types/react-dom": "^16.9.5",
    "@types/react-select": "^3.0.10",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-select": "^3.0.8",
    "typescript": "^3.7.5"

Run Code Online (Sandbox Code Playgroud)

小智 10

您需要将选项数组中的值设置为 Select 组件的当前值。

然而,这并不是唯一的问题,因为 onChange 函数的类型签名有些令人困惑。您需要为选项定义类型并在 onChange 函数签名中使用“ValueType”。

这是一个工作示例

type OptionType = {
  value: string;
  label: string;
};

const options: OptionType[] = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" },
  { value: "vanilla", label: "Vanilla" }
];

const MyComponent = () => {
  const [selectedOption, setSelectedOption] = useState<ValueType<OptionType>>(options[0]);

  const handleChange = (option: ValueType<OptionType>) => {
    setSelectedOption(option);
  };

  return (
    <Select
      value={selectedOption}
      onChange={option => handleChange(option)}
      options={options}
    />
  );
};
Run Code Online (Sandbox Code Playgroud)

有关该问题的更多信息https://github.com/JedWatson/react-select/issues/2902

带有上述代码的沙盒 https://codesandbox.io/s/angry-frost-5bh1o


use*_*824 1

  <Select
    value={selectedOption}
    onChange={(option) => handleChange(option)}
    options={options}
  />
Run Code Online (Sandbox Code Playgroud)

问题是value必须是 中的条目options。您已将状态设置为字符串“chocolate”,并且它抛出一个错误,表明它不是同一类型。

如果您将状态更新为:

  const [selectedOption, setSelectedOption] = useState(options[0]);
Run Code Online (Sandbox Code Playgroud)

现在就可以了。