我有一個包含三個孩子的復合組件,我需要宣告每個孩子的型別。所有孩子都作業正常,除了一個具有泛型型別的孩子總是回傳一個需要 0 個引數并得到 1 的錯誤。

這是我要更改的型別

這是我使用組件時出現的錯誤資訊
這是組件本身
import React from 'react'
import Select from 'react-select'
import { SelectInputI } from '../models'
export function SelectInput<T>({
value: inputValue,
onChange: onInputChange,
onBlur,
getSelectValue,
error,
name,
handleOptionLabel,
handleOptionValue,
options,
placeholder,
}: SelectInputI<T>) {
return (
<>
<Select<T>
name={name}
defaultValue={inputValue}
value={inputValue}
isSearchable
placeholder={placeholder}
onChange={(e: any) => {
onInputChange(name, () => getSelectValue())(e)
}}
getOptionLabel={handleOptionLabel}
getOptionValue={handleOptionValue}
options={options}
onBlur={onBlur}
/>
{error && <p>{error}</p>}
</>
)
}

uj5u.com熱心網友回復:
你解決React.FC<SelectInputI<any>>的一個不是泛型型別。
此外,React.FC不能在呼叫時使其通用,這是您不應該使用它的眾多原因之一。
你基本上是這樣做的:
type Generic<T> = { value: T }
type A = Generic<any>
type B = A<{ test: boolean }> // Type 'A' is not generic.(2315)
你需要做的是:
type Generic<T> = { value: T }
type A<T> = Generic<T> // type A is now generic
type B = A<{ test: boolean }> // fine
你省略了SelectInputI型別,所以讓我們假設它是這樣的:
type SelectInputI<T> = {
value: T
onChange: (newValue: T) => void
}
如果你想要一個使用該型別作為道具的通用組件,并在value那里接受一個通用型別,那么它的型別將是:
<T>(props: SelectInputI<T>) => JSX.Element
因此,如果我用該型別存根一個物件:
declare const NewSearch: {
SelectInput: <T>(props: SelectInputI<T>) => JSX.Element
}
然后它會按您的預期作業。
const result = <NewSearch.SelectInput<{ label: string, value: string }>
value={{ label: 'a', value: 'b' }}
onChange={(newValue) => console.log(newValue)}
/>
看游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/528372.html
標籤:反应打字稿仿制药
上一篇:Max的MakeGenericMethod在.Net6中不起作用
下一篇:Typescript抽象類擴展自mixin(class,generic)/mixin(classA,classB|classD...)
