首页 > 解决方案 > 如何使用打字稿和自定义样式的定义使用 react-select 进行选择

问题描述

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

到目前为止的组件如下所示:

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

以及 的定义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,
    …

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

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

标签: reactjstypescriptreact-select

解决方案


您可以使用StyleConfigwhich 键入整个样式对象,无需手动键入每个参数。但在此之前,您需要安装@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
    };
  }
};
export function App() {
  return (
    <Select options={options} styles={selectStyle} />
  );
}

现场演示

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


推荐阅读