Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React:接受泛型接口作为prop_Reactjs_Typescript - Fatal编程技术网

Reactjs React:接受泛型接口作为prop

Reactjs React:接受泛型接口作为prop,reactjs,typescript,Reactjs,Typescript,使用React中的Typescript,我希望创建一个接受通用接口的prop类型 interface Waffle { startEating: number; endEating: number; ... } interface Pancake { pourSyrup: boolean; bake: boolean; ... } interface classProps { anInterface: ???; } class Food extends React.C

使用React中的Typescript,我希望创建一个接受通用接口的prop类型

interface Waffle
{
  startEating: number;
  endEating: number;
  ...
}
interface Pancake
{
  pourSyrup: boolean;
  bake: boolean;
  ...
}
interface classProps
{
  anInterface: ???;
}
class Food extends React.Component<classProps, null>
{ ... }
接口华夫格
{
开始:编号;
可爱:数量;
...
}
接口煎饼
{
布尔型;
烘焙:布尔;
...
}
接口类道具
{
接口:???;
}
类。组件
{ ... }
在本例中,我如何将'anInterface'属性键入interface类型;也就是说,要接受一块华夫饼或煎饼?

这应该可以:

接口华夫格{
开始:编号;
可爱:数量;
}
接口煎饼{
布尔型;
烘焙:布尔;
}
接口类道具{
接口:T;
}
类。组件{
...
}
请注意,如果呈现取决于您正在接收的接口的类型,而您在编译时不知道接口的类型,则泛型将无法工作。

请查看此处:

类型道具={
数据:D;
选择器:(数据:D)=>S;
};
常量Comp=(props:props)=>null;
常数结果=(
“fg”}
/>
); // 好啊
常量结果2=(
); 

示例取自my

,您可以声明一个基本接口,
Waffle
Pancake
将从中扩展。然后您可以将
接口
属性设置为声明接口的类型:关键问题是您是否知道在编译时组件将接收什么类型。如果是这样,@luckongas的回答就可以了。如果不是,那么问题就更复杂了……我同意。如果组件的呈现取决于接收到的接口类型,而OP不知道它是什么类型,那么解决方案将不起作用。不,我不知道它在编译时将接收什么类型。它将始终是所选接口之一;在这种情况下,它将始终是华夫饼或煎饼。