首页 > 解决方案 > 有没有办法通过道具传递接口?

问题描述

我想知道是否有办法通过道具传递接口。

例如,下面的组件尝试将接口传递给 Apple 组件。

import Apple from "./";

Interface A {
  name: string;
}

const Component = () => {
  return (
     <Apple 
       ...
       type={A} <--- Pass it in like this
     />
   );
}

1-以上可以做到吗?

2-如果是这样,Apple组件内的接口类型是什么?

标签: reactjstypescript

解决方案


你不能通过 props 传递接口,因为它只存在于构建时,而不是运行时。如果你想在某个地方打发时间,你可以使用泛型。

export interface AppleProps<T> { /* ... */ }

export function Apple<T>(props: AppleProps<T>) { /* ... */ }

// ...

import Apple from "./";

interface A {
  name: string;
}

const Component = () => {
  return (
     // You can provide generic arguments for react elements
     <Apple<A> />
   );
}

推荐阅读