如何使用带有自定义样式定义的 typescript 使用 react-select

gus*_*ani 8 typescript reactjs react-select

我想知道如何使用 react-select 很好地向 Select 添加类型。

到目前为止的组件看起来像这样:

const Select: React.FC<Select> = (
  {defaultValue, onChange, options}: Select) => (
  <ReactSelect
    styles={selectStyles}
    …
  </ReactSelect>
Run Code Online (Sandbox Code Playgroud)

和的定义selectStyles

interface HoverProps {
  bowShadow: string
  border: string
}

interface ControlComponentCSSProperties extends CSSProperties {
  '&:hover': HoverProps
}

const selectStyles = {
  control: (
    provided: CSSProperties,
    state: Props<{label: string; value: string}> | Props<Record<string, unknown>>
  ): ControlComponentCSSProperties => ({
    ...provided,
    '&:hover': {
      bowShadow: 'none',
      border: 'none',
    },
    border: 'none',
    borderRadius: input.border.radius,
    borderBottomLeftRadius: state.menuIsOpen ? 0 : input.border.radius,
    borderBottomRightRadius: state.menuIsOpen ? 0 : input.border.radius,
    …
Run Code Online (Sandbox Code Playgroud)

这通过了,tsc但肯定有更简单的方法来输入这个selectStyles对象。

感谢您的帮助,为我指明更好的方向。干杯!

Nea*_*arl 20

您可以使用StyleConfig它来输入整个样式对象,从而无需手动输入每个参数。但在此之前,您需要安装@types/react-select软件包。

StyleConfig要求您根据此处的声明传递至少 2 个泛型类型变量。

  • OptionType: 的选项类型react-select。根据,默认OptionType{ label: string; value: string }
  • IsMulti: 一个布尔值,用于确定您是否可以选择多个值。

把它们放在一起,我们会有这样的东西:

import Select, { StylesConfig } from 'react-select';

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

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

const customControlStyles: CSSProperties = {
  color: "white",
  borderColor: "pink"
};

type IsMulti = false;

const selectStyle: StylesConfig<MyOptionType, IsMulti> = {
  control: (provided, state) => {
    // provided has CSSObject type
    // state has ControlProps type

    // return type is CSSObject which means this line will throw error if uncommented
    // return false;

    return {
      ...provided,
      ...customControlStyles
    };
  }
};
Run Code Online (Sandbox Code Playgroud)
export function App() {
  return (
    <Select options={options} styles={selectStyle} />
  );
}
Run Code Online (Sandbox Code Playgroud)

现场演示

编辑 63696310/how-to-use-typescript-with-the-definition-of-custom-styles-for-a-select-using-re

  • 非常感谢。我仍然必须使用 ``` state: Props&lt;Record&lt;string,unknown&gt;&gt; ``` 因为 ControlProps 的变体没有通过。但是你的建议使实施变得更加清晰,非常感谢 (2认同)