typescript 如何在React-Select中为onChange事件的选定选项添加自定义类型

oprakyz7  于 2023-06-24  发布在  TypeScript
关注(0)|答案(1)|浏览(160)

我使用react-select创建了一个SelectBox组件,并为其添加了onChange事件。我想在onChange事件中的选定选项中添加类型“SelectedItemType”。然而,onChnage事件的类型是(属性)onChange?:((newValue:未知,actionMeta:ActionMeta)=> void)|undefined因此选项类型是unknown,它阻止我添加unknown以外的类型,这使得从选项中提取对象属性变得困难

import { ForwardedRef, forwardRef } from "react";
import Select, { SelectInstance } from "react-select";

export type SelectedItemType = {
value: string;
label: string;
};

export type SelectProps = {
options: SelectedItemType[];
ref?: ForwardedRef<SelectInstance>;
onChange: (selectedItem: unknown) => void;
};

const SelectBox: React.FC<SelectProps> = forwardRef<
SelectInstance,
SelectProps
>(({ options, onChange, ...props }, ref) => {
return (
<Select
options={options}
ref={ref}
{...props}
onChange={(newValue: unknown) => onChange(newValue)}
/>
);
});

export default SelectBox;

在上面的代码中,我想将SelectedItemType添加到onChange的newValue中。但是它抛出了一个错误,说Type '(newValue:SelectedItemType)=> void'不可赋值给类型'(newValue:未知,actionMeta:ActionMeta)=> void '。参数“newValue”和“newValue”的类型不兼容。类型“unknown”不能分配给类型“SelectedItemType”。当我想从选项中提取值和标签时,如何将此自定义类型添加到选项中。

bvn4nwqk

bvn4nwqk1#

如果你想将类型赋值给newValue,以便在onChange函数中很容易地访问它的属性,那么可以通过做两个主要的修改来完成。
1.将SelectPropsonChange属性类型更改为

export type SelectProps = {
  options: SelectedItemType[];
  ref?: ForwardedRef<SelectInstance>;
  onChange: (selectedItem: SelectedItemType) => void;
};

1.则在select组件中,其onChange将被修改为

<Select
      options={options}
      ref={ref}
      {...props}
      onChange={(newValue: unknown) => onChange(newValue as SelectedItemType)}
    />

然后使用SelectBox组件,如下所示:

<SelectBox
        options={[
          { label: "A", value: "1" },
          { label: "B", value: "2" }
        ]}
        onChange={function (selectedItem: SelectedItemType): void {
          console.log(selectedItem.value);
        }}
      />

下面是文件App.tsx的完整代码

import { ForwardedRef, forwardRef } from "react";
import Select, { SelectInstance } from "react-select";

export type SelectedItemType = {
  value: string;
  label: string;
};

export type SelectProps = {
  options: SelectedItemType[];
  ref?: ForwardedRef<SelectInstance>;
  onChange: (selectedItem: SelectedItemType) => void;
};

const SelectBox: React.FC<SelectProps> = forwardRef<
  SelectInstance,
  SelectProps
>(({ options, onChange, ...props }, ref) => {
  return (
    <Select
      options={options}
      ref={ref}
      {...props}
      onChange={(newValue: unknown) => onChange(newValue as SelectedItemType)}
    />
  );
});

export default function App() {
  return (
    <div className="App">
      <SelectBox
        options={[
          { label: "A", value: "1" },
          { label: "B", value: "2" }
        ]}
        onChange={function (selectedItem: SelectedItemType): void {
          console.log(selectedItem.value);
        }}
      />
    </div>
  );
}

相关问题