reactjs - 如何使用打字稿和自定义样式的定义使用 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
对象。
感谢您的帮助,为我指明更好的方向。干杯!
解决方案
您可以使用StyleConfig
which 键入整个样式对象,无需手动键入每个参数。但在此之前,您需要安装@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} />
);
}
现场演示
推荐阅读
- python - 如何遍历字典并根据键为变量赋值?
- image - 如何从word doc中提取图片
- android - 未找到 Kotlin 插件
- javascript - 使用 jquery 构建嵌套对象/数组
- jquery - jQuery验证追加输入
- azure - 如何建立 IoTCentral/IoT Edge 开发环境
- php - 当我转到下一个问题时,有人可以帮我保持选中单选按钮吗?
- kotlin - Jetpack compose for desktop:在后台运行应用程序?
- c# - Transform.FindChild(string) 已过时。我应该输入什么?我正在通过一个旧教程学习 C#/unity
- swift - 无法安装最新版本的 Cocoapods