类型“ForwardedRef<HTMLInputElement>”不可分配给类型“LegacyRef<Select<Option, false, GroupBase<Option>>> |不明确的'。在反应选择中

问题描述 投票:0回答:1

当我在使用 React-Select 时在 Select 组件中使用forwardRef 时,出现此 TypeScript 错误。

Type 'ForwardedRef<HTMLInputElement>' is not assignable to type
'LegacyRef<Select<Option, false, GroupBase<Option>>> | undefined'.
import Select from "react-select";

export const SelectInput = forwardRef<HTMLInputElement, SelectInputProps>(
 (props, ref) =>{
    ...

    return(
     <div>
       <Select
         key="random-key"
         ref={ref}
         ....
        />
     </div>
    )
 }
)

我使用了相同的类型和带有输入元素的forwardRef,一切似乎都很好,但我在这里遇到了问题。我已经尝试了几种解决方案,例如这个 useRef TypeScript - 不可分配给类型 LegacyRef 它对我不起作用。

这是错误的完整日志

Type 'ForwardedRef<HTMLInputElement>' is not assignable to type 'LegacyRef<Select<Option, false, GroupBase<Option>>> | undefined'.

Type '(instance: HTMLInputElement | null) => void' is not assignable to type 'LegacyRef<Select<Option, false, GroupBase<Option>>> | undefined'.
    Type '(instance: HTMLInputElement | null) => void' is not assignable to type '(instance: Select<Option, false, GroupBase<Option>> | null) => void | (() => VoidOrUndefinedOnly)'.
      Types of parameters 'instance' and 'instance' are incompatible.
        Type 'Select<Option, false, GroupBase<Option>> | null' is not assignable to type 'HTMLInputElement | null'.
          Type 'Select<Option, false, GroupBase<Option>>' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 352 more.
javascript reactjs typescript types react-select
1个回答
0
投票

想找到更简单的方法吗?像这样摆脱forwardRef组件

export const SelectInput = <Option, IsMulti extends boolean = false, Group extends GroupBase<Option> = GroupBase<Option>>({
    id,
    name,
    className,
    //...other select input properties
    ...props,
}: SelectInputProps<Option, IsMulti, Group> & { myRef: React.Ref<HTMLDivElement> }) => {
    return (
        <div>
            <Select
                key="random-key"
                ref={props.myRef}
                //...
            />
        </div>
    )
}

用途:

interface OptionType { // convert into your own type
    id: number
    name: string
}

const ParentComponent = () => {
    const selectRef = useRef<HTMLDivElement>(null)

    useEffect(() => {
        if (selectRef.current) console.log("select component: ", selectRef.current)
    }, [])

    return (
        <Select<OptionType>
            myRef={selectRef}
            options={options}
            //...
        />
        
    )
}
© www.soinside.com 2019 - 2024. All rights reserved.