我想知道如何使用react-select很好地向Select添加类型。
到目前为止,该组件如下所示:
weights_init
和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
对象。
将感谢您为我指出更好方向的帮助。 干杯!
答案 0 :(得分:5)
是的。您还可以键入整个样式对象,从而无需手动键入每个参数。但是在此之前,您需要安装@types/react-select
import Select, { StylesConfig } from 'react-select';
const selectStyle: StylesConfig = {
control: (provided, state) => {
// provided has CSSProperties type
// state has ControlProps<{}> type
// return type is CSSProperties which means this line will throw
// error if uncommented
// return false;
return {
...provided,
...yourCustomStyle,
};
},
}
const Select: React.FC<Select> = (
{defaultValue, onChange, options}: Select) => (
<ReactSelect
styles={selectStyles}
…
</ReactSelect>
)