簡體   English   中英

當道具在 React、Typescript 中可以有多種類型時,如何傳遞特定道具?

[英]How to pass a specific prop when the props can have multiple types in React, Typescript?

Props 與不同類型數據的接口:

interface ResultProp {
    type: string
    data: {} | AProp | BProp | CProp | DProp
}

Cardview 將根據 props.type 將 props 數據傳遞給相應的組件:

const Cardview:React.FC<ResultProp> = (props) => {
    const renderComponent = () => {
        switch(props.type){
            case "aprop":
                return <A {...props.data} />    // Type mismatch here
            // rest of the types ...
        }
    }
    return (
        <div className="cardview">
            {() => renderComponent}
        </div>
    )
}

從 Cardview 接收 props 的組件:

const A: React.FC<AProp> = (props) => {
    return (
        <div>
        </div>
    )
}

為了讓 TypeScript 理解props.typeprops.data之間的關系,你需要使用一個有區別的聯合

type ResultProp = {type: "aprop", data: AProp} | {type: "bprop", data: BProp} | ...;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM