Hec*_*tor 1 typescript reactjs
我想知道是否有办法通过 prop 传递接口。
例如,下面的组件尝试将接口传递给 Apple 组件。
import Apple from "./";
Interface A {
name: string;
}
const Component = () => {
return (
<Apple
...
type={A} <--- Pass it in like this
/>
);
}
Run Code Online (Sandbox Code Playgroud)
1-以上可以做到吗?
2-如果是的话,Apple 组件内部的接口类型是什么?
小智 5
您不能通过 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> />
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1700 次 |
| 最近记录: |