[英]How to type a prop which is a function component in react typescript
我有一個反應組件,它接受一個反應 function 組件作為道具。
我的代碼:
interface ComponentBProps {
someComponent?: React.ComponentType;
msg: string;
}
function ComponentB({someComponent: SomeComponent, msg}: ComponentBProps ) {
return (
<div>
{
SomeComponent && <SomeComponent>
<div>
{msg}
</div>
</SomeComponent>
}
</div>
);
}
function ComponentA() {
return (
<ComponentB
someComponent={({children}) => <div>{children}</div>}
msg="msg"
/>
);
}
它給了我錯誤
Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes'.
<SomeComponent>
<div>
和
Property 'children' does not exist on type '{}'.
<ComponentB
someComponent={({children}) => <div>{children}</div>}
msg="msg"
/>
我應該分配給什么類型
someComponent?: React.ComponentType;
反應版本: ^18.2.0
如果你想強制執行特定的 React 組件,則以下方法有效。
const ComponentA: React.FC<{ name: string }> = ({ name }) => <div>hello {name}</div>;
interface PropsB {
component: typeof ComponentA;
}
const ComponentB: React.FC<PropsB> = ({ component: Component }) => (
<div>
<Component name='John' />
</div>
);
<ComponentB component={ComponentA} />;
我喜歡使用從 React 導入的FunctionComponent
type Props = {
component: FunctionComponent<OtherProps>
}
export function SomeComponent({ component: Component }: Props) {
return <Component />
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.