[英]How to type a prop which is a function component in react typescript
I have a react component which accepts a react function component as a prop.我有一个反应组件,它接受一个反应 function 组件作为道具。
My code:我的代码:
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"
/>
);
}
It gives me the error它给了我错误
Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes'.
<SomeComponent>
<div>
and和
Property 'children' does not exist on type '{}'.
<ComponentB
someComponent={({children}) => <div>{children}</div>}
msg="msg"
/>
what type should I assign to我应该分配给什么类型
someComponent?: React.ComponentType;
react version: ^18.2.0
反应版本:
^18.2.0
The following works if you want to enforce a specific React component.如果你想强制执行特定的 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} />;
I like to use FunctionComponent imported from React我喜欢使用从 React 导入的FunctionComponent
type Props = {
component: FunctionComponent<OtherProps>
}
export function SomeComponent({ component: Component }: Props) {
return <Component />
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.