当 props 在 React、Typescript 中可以有多种类型时,如何传递特定的 prop?
How to pass a specific prop when the props can have multiple types in React, Typescript?
具有不同类型数据的道具接口:
interface ResultProp {
type: string
data: {} | AProp | BProp | CProp | DProp
}
Cardview 将根据 props.type:
将道具数据传递给相应的组件
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 接收道具:
const A: React.FC<AProp> = (props) => {
return (
<div>
</div>
)
}
为了让 TypeScript 理解 props.type
和 props.data
之间的关系,您需要使用 discriminated union:
type ResultProp = {type: "aprop", data: AProp} | {type: "bprop", data: BProp} | ...;
具有不同类型数据的道具接口:
interface ResultProp {
type: string
data: {} | AProp | BProp | CProp | DProp
}
Cardview 将根据 props.type:
将道具数据传递给相应的组件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 接收道具:
const A: React.FC<AProp> = (props) => {
return (
<div>
</div>
)
}
为了让 TypeScript 理解 props.type
和 props.data
之间的关系,您需要使用 discriminated union:
type ResultProp = {type: "aprop", data: AProp} | {type: "bprop", data: BProp} | ...;