React-Select自定义DropdownIndicator遇ESLint any值不安全赋值错误求助
解决react-select自定义DropdownIndicator的ESLint类型错误
你遇到的ESLint错误“Unsafe member access .selectProps on an any value”,本质是TypeScript和ESLint没能正确识别selectProps的具体类型,默认将其判定为any类型,导致访问.menuIsOpen时触发不安全访问警告。下面提供两种可行的解决方法:
方案一:给selectProps添加类型断言
直接通过类型断言明确selectProps的类型,快速消除错误:
import { useState } from "react"; import Select, { DropdownIndicatorProps, SelectProps } from "react-select"; import { OverviewTable } from "../components/OverviewTable"; type CustomOptionType = { value: string; label: string; }; const DropdownIndicator = ({ selectProps, }: DropdownIndicatorProps<CustomOptionType, false>) => { // 明确指定selectProps的类型 const { menuIsOpen } = selectProps as SelectProps<CustomOptionType, false>; return menuIsOpen ? ( <i className="fa-solid fa-angle-up text-xs"></i> ) : ( <i className="fa-solid fa-angle-down text-xs"></i> ); }; <Select options={options} value={selectedUnit} onChange={handleChange} inputId="unit-select" components={{ IndicatorSeparator: () => null, ClearIndicator: () => null, DropdownIndicator }} />
方案二:扩展自定义Props类型
如果需要更严谨的类型约束,可以手动扩展DropdownIndicatorProps,确保selectProps的类型被完全覆盖:
import { useState } from "react"; import Select, { DropdownIndicatorProps, SelectProps } from "react-select"; import { OverviewTable } from "../components/OverviewTable"; type CustomOptionType = { value: string; label: string; }; // 自定义组件Props类型,明确selectProps的结构 type CustomDropdownIndicatorProps = DropdownIndicatorProps<CustomOptionType, false> & { selectProps: SelectProps<CustomOptionType, false>; }; const DropdownIndicator = ({ selectProps, }: CustomDropdownIndicatorProps) => { const { menuIsOpen } = selectProps; return menuIsOpen ? ( <i className="fa-solid fa-angle-up text-xs"></i> ) : ( <i className="fa-solid fa-angle-down text-xs"></i> ); }; <Select options={options} value={selectedUnit} onChange={handleChange} inputId="unit-select" components={{ IndicatorSeparator: () => null, ClearIndicator: () => null, DropdownIndicator }} />
这两种方法都能让ESLint正确识别selectProps的类型,从而消除错误提示。方案一适合快速修复,方案二则更适配类型严格的项目。
内容的提问来源于stack exchange,提问作者Brunol55
相关产品推荐
相关产品推荐

