简体   繁体   English

反应选择和打字稿:类型“字符串”不可分配给类型“ValueType”<OptionTypeBase> &#39;

[英]react-select and typescript: Type 'string' is not assignable to type 'ValueType<OptionTypeBase>'

I am trying to create an example component that uses react-select with typescript.我正在尝试创建一个使用 react-select 和 typescript 的示例组件。

For this, I created a functional component and added the default example from react-select docs :为此,我创建了一个功能组件并添加了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}
        />
    );

};

However, this gives me an error:但是,这给了我一个错误:

 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>'.

what am I doing wrong?我究竟做错了什么?

My packages are:我的包裹是:

    "@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"

You need to set a value from your options array as the current value of Select component.您需要将选项数组中的一个值设置为 Select 组件的当前值。

This however is not the only problem because the type signature of the onChange function is somewhat confusing.然而,这不是唯一的问题,因为 onChange 函数的类型签名有些混乱。 You'll need to define a type for the options and use `ValueType´ in the onChange function signature.您需要为选项定义一个类型并在 onChange 函数签名中使用“ValueType”。

Here's a working example这是一个工作示例

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}
    />
  );
};

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

Sandbox with the code above https://codesandbox.io/s/angry-frost-5bh1o上面代码的沙箱https://codesandbox.io/s/angry-frost-5bh1o

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

The issue is value must be an entry within options .问题是value必须是options中的一个条目。 You have set the state to the string "chocolate" and it's throwing an error indicating that isn't of the same type.您已将状态设置为字符串“chocolate”,它会抛出一个错误,表明它不是同一类型。

If you update your state to something like:如果您将状态更新为:

  const [selectedOption, setSelectedOption] = useState(options[0]);

It'll now work.它现在可以工作了。

import AsyncSelect from 'react-select/async';  

interface ColourOption {
    readonly value: string;
    readonly label: string;
    readonly color: string;
    readonly isFixed?: boolean;
    readonly isDisabled?: boolean;
  }
  
  const colourOptions: readonly ColourOption[] = [
    { value: 'ocean', label: 'Ocean', color: '#00B8D9', isFixed: true },
    { value: 'blue', label: 'Blue', color: '#0052CC', isDisabled: true },
    { value: 'purple', label: 'Purple', color: '#5243AA' },
    { value: 'red', label: 'Red', color: '#FF5630', isFixed: true },
    { value: 'orange', label: 'Orange', color: '#FF8B00' }
  ];
  

  const filterColors = (inputValue: string) => {
    return colourOptions.filter((i) =>
      i.label.toLowerCase().includes(inputValue.toLowerCase())
    );
  };
  
  const promiseOptions = (inputValue: string) =>
    new Promise<ColourOption[]>((resolve) => {
      setTimeout(() => {
        resolve(filterColors(inputValue));
      }, 1000);
    });    


<AsyncSelect 
    isMulti
    cacheOptions
    defaultOptions
    placeholder ={"Start typing to add another conditions"}
    loadOptions={promiseOptions}
    />

Try to do something like this:尝试做这样的事情:

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

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

const MyComponent = () => {

const [selectedOption, setSelectedOption] = useState<Pick<TSelectOption, 'value'>>('chocolate');

const handleChange = (option: SingleValue<Pick<TSelectOption, 'value'>>) => {
    setSelectedOption(option);
};

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

};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 react-select typescript 问题 - 通用类型“ValueType”需要 2 个类型参数。ts(2314) - react-select typescript issue - Generic type 'ValueType' requires 2 type argument(s).ts(2314) Typescript React - 类型“字符串”不可分配给类型“外观” - Typescript React - Type 'string' is not assignable to type 'Appearance' React TypeScript:类型“string []”不可分配给类型“never []” - React TypeScript: Type 'string[]' is not assignable to type 'never[]' 使用TypeScript进行反应:类型“ {}”不可分配给类型 - React with TypeScript: Type '{}' is not assignable to type 打字稿:类型“字符串”不可分配给类型 - Typescript: Type 'string' is not assignable to type 在反应 typescript 中,类型“字符串”不可分配给类型“从不”并且类型“未知”不可分配给类型“从不”错误 - Type 'string' is not assignable to type 'never' and Type 'unknown' is not assignable to type 'never' error in react typescript React,typescript - 'string | 类型的参数 null' 不能分配给“字符串”类型的参数 - React, typescript - Argument of type 'string | null' is not assignable to parameter of type 'string' TextArea 中的 React Typescript 错误:类型“字符串”不可分配给类型编号 - React Typescript error in TextArea : Type 'string' is not assignable to type number React Typescript - 'string' 类型的参数不可分配给 useState 中的类型参数 - React Typescript - Argument of type 'string' is not assignable to parameter of type within useState 输入“日期范围”<date | null> ' 不可分配给类型 'ValueType'</date> - Type 'DateRange<Date | null>' is not assignable to type 'ValueType'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM