如何在打字稿中为 React-Select 定义 onChange 处理程序

Mic*_*ael 14 typescript react-select

我无法正确输入 onchange 函数。我创建了一个处理函数,但打字稿一直抱怨类型不匹配。

我的功能:

private handleChange(options: Array<{label: string, value: number}>) {
}
Run Code Online (Sandbox Code Playgroud)

打字稿错误:

src/questionnaire-elements/AssessmentFactorSearch.tsx (43,9): Type '{ ref: "select"; name: string; backspaceToRemoveMessage: ""; value: { label: string; value: IAsse...' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Async<OptionValues>> & Readonly<{ children?: React...'. Type '{ ref: "select"; name: string; backspaceToRemoveMessage: ""; value: { label: string; value: IAsse...' is not assignable to type 'Readonly<ReactAsyncSelectProps<OptionValues>>'. Types of property 'onChange' are incompatible. Type '(options: { label: string; value: number; }[]) => void' is not assignable to type 'OnChangeHandler<OptionValues, Option<OptionValues> | Option<OptionValues>[]> | undefined'. Type '(options: { label: string; value: number; }[]) => void' is not assignable to type 'OnChangeHandler<OptionValues, Option<OptionValues> | Option<OptionValues>[]>'. (2322)

如何键入 onchange 方法?

dal*_*usd 9

基于https://github.com/JedWatson/react-select/issues/2902,只需像这样编写您的处理程序:

// define your option type
type MyOption = {label: string, value: number}

// ...

  // define your onChange handler:
  private handleChange = (selected?: MyOption | MyOption[] | null) => {
    /** Code **/
  }
Run Code Online (Sandbox Code Playgroud)

请注意部分MyOption | MyOption[] | null,它与onChangereact-select 库中的定义匹配相同的结构。只做你自己的MyOption类型。

该问题线程中的另一个示例也表明您可以内联传递函数,在这种情况下,将自动推断处理程序参数的类型:

<Select
  onChange={selectedOption /* type is automatically inferred here */ => {
    if (Array.isArray(selectedOption)) {
      throw new Error("Unexpected type passed to ReactSelect onChange handler");
    }

    doSomethingWithSelectedValue(selectedOption.value);
  }}
  ...
/>
Run Code Online (Sandbox Code Playgroud)


Ser*_*kin 7

至于 react-select ˆ3.1.0下面的代码应该可以工作:

import {ValueType, ActionMeta} from 'react-select';

type MyOptionType = { label: string, value: number }

type OnChange = (value: ValueType<MyOptionType>, actionMeta: ActionMeta<MyOptionType>) => void;
Run Code Online (Sandbox Code Playgroud)