我正在創建一個將在兩個不同組件中使用的組件。在組件 A 中,主引數將輸入為 typeA,回呼將具有 typeA 引數,而在另一個組件 B 中,主引數將輸入為 typeB,回呼將具有 typeB 引數。我在新組件 1 中遇到錯誤,因為回呼無法獲取 typeA 的變數 | typeB(這是有道理的)。
這是它的外觀的簡單版本:
type Props = {
option: typeA | typeB;
callback: (e, a: typeA) => void | (e, b: typeB) => void:
}
export const Component1 : (props: Props) => {
return (
<Button onClick={() => {props.callback(props.option)}>
{props.option.label}
</Button>
}
有沒有辦法在 props 中將型別關聯在一起,以便說來自組件 B 的回呼只會關聯到 typeB 的引數?
uj5u.com熱心網友回復:
我認為你需要的是Typescript 中的泛型。您基本上將型別引數(變數T)傳遞給Props型別,在您定義特定組件的地方。
type typeA = {
label: string
}
type typeB = {
label: number
}
type Props<T> = {
option: T;
callback: (e: React.MouseEvent<HTMLButtonElement, MouseEvent>, a: T) => void | ((e: React.MouseEvent<HTMLButtonElement, MouseEvent>, b: T) => void);
}
export const Component1 = (props: Props<typeA>) => {
return (
<button onClick={(e) => {props.callback(e, props.option)}}>
{props.option.label}
</button>
)
}
export const Component2 = (props: Props<typeB>) => {
return (
<button onClick={(e) => {props.callback(e, props.option)}}>
{props.option.label}
</button>
)
}
uj5u.com熱心網友回復:
type Props<T> = {
option: T;
callback: (e, a: T) => void
}
export const Component1 : (props: Props<Type1>|Props<Type2>) => {
return (
<Button onClick={() => {props.callback(props.option)}>
{props.option.label}
</Button>
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/429987.html
上一篇:當物件由類組成時訪問物件屬性
