根据 react-select docs,我可以像这样访问传递给 Select 主体的我自己的参数:
const customStyles = {
menu: (provided, state) => ({
...provided,
width: state.selectProps.width,
borderBottom: '1px dotted pink',
color: state.selectProps.menuColor,
padding: 20,
}),
control: (_, { selectProps: { width }}) => ({
width: width
}),
singleValue: (provided, state) => {
const opacity = state.isDisabled ? 0.5 : 1;
const transition = 'opacity 300ms';
return { ...provided, opacity, transition };
}
}
但是如果我在打字稿中有这样的东西
const customStyles: SelectProps["styles"] = {
valueContainer: (provided, { selectProps: { size } }) => {
const px = {
sm: "0.75rem",
md: "1rem",
lg: "1rem"
};
return {
...provided,
padding: `0.125rem ${px[size]}`
};
},
};
${px[size]}
部分抛出错误
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ sm: string; md: string; lg: string; }'.
答案 0 :(得分:1)
表示传入的 size
是 any
类型,打字稿不知道它是否是 sm
md
lg
的键之一。< /p>
方式01:使用cast
通知打字稿,大小是sm
md
lg
const px = {
sm: "0.75rem",
md: "1rem",
lg: "1rem"
};
px[size as 'sm' | 'md' | 'lg']
方法 02:为 px
设置一个类型并使用其键进行转换
type PxType = { [k in 'sm' | 'md' | 'lg']: string }
const px: PxType = {
sm: "0.75rem",
md: "1rem",
lg: "1rem"
};
px[size as keyof PxType]