[英]How to pass a specific prop when the props can have multiple types in React, Typescript?
Props Interface with data of different types: Props 与不同类型数据的接口:
interface ResultProp {
type: string
data: {} | AProp | BProp | CProp | DProp
}
Cardview will pass props data to respective component based on the props.type: 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>
)
}
Component receiving props from Cardview:从 Cardview 接收 props 的组件:
const A: React.FC<AProp> = (props) => {
return (
<div>
</div>
)
}
为了让 TypeScript 理解props.type
和props.data
之间的关系,你需要使用一个有区别的联合:
type ResultProp = {type: "aprop", data: AProp} | {type: "bprop", data: BProp} | ...;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.