Typescript下react-select自定义Input组件InputProps类型不兼容问题
解决方案
react-select 内置了完整的 InputProps 泛型接口,你不需要自定义类型,直接引入使用即可:
- 首先从 react-select 包中导入核心类型和内置组件
import { InputProps, components } from 'react-select'; // 你业务中定义的 Option 结构,根据自己的实际场景修改 type CustomOption = { label: string; value: string; // 其他自定义字段 };
- 给 CustomInput 加上正确的泛型类型声明
// 泛型第一个参数为你的Option类型,第二个为是否支持多选的布尔值 const CustomInput = <Option extends CustomOption, IsMulti extends boolean = false>( inputProps: InputProps<Option, IsMulti> ) => { // 直接取输入框当前的value,有完整类型提示 const currentInputValue = inputProps.value; // 全量options、选中值等select全局属性都挂载在selectProps字段下 const allOptions = inputProps.selectProps.options; const selectedValue = inputProps.selectProps.value; return ( <> <components.Input {...inputProps} /> {/* 你的自定义逻辑 */} </> ); };
注:如果是老版本的 TypeScript + TSX 语法,泛型声明的右尖括号前加个逗号
<Option extends CustomOption,>避免被识别为HTML标签。
如果你有自定义分组需求,给InputProps传入第三个泛型参数指定分组类型即可,日常单/多选场景不需要额外配置,修改IsMulti泛型参数就能自动适配多选场景的value类型。
这样修改后完全不需要any类型,所有属性都有类型提示,lint警告也会全部消除。
内容的提问来源于stack exchange,提问作者SuuSoJeat
相关产品推荐
相关产品推荐

