[英]How do you assert the type of a component as prop?
I am trying to pass a component as prop.我正在尝试将组件作为道具传递。
The component:组件:
export type ItemProps= {
//...
};
export const Item = ({ /* ... */ }: ItemProps) => {
return (
//...
);
};
Where I'm attempting to pass it:我试图通过它的地方:
type ParentProps= {
//...
item: ReactElement<ItemProps>;
};
export const Parent = ({ /* ... */, item }: ParentProps) => {
return (
<>
{item}
</>
);
};
What I'm trying to achieve:我想要达到的目标:
export const Main = () => {
return (
<Parent item={ <Item /> } />
);
};
As you can see, I am trying to pass the Item
component as a prop in the Parent
component.如您所见,我试图将
Item
组件作为 prop 传递给Parent
组件。 As of now, this works , but it seems that using ReactElement loosens the type to ReactElement<ItemProps, string | JSXElementConstructor<any>>
截至目前,这是可行的,但似乎使用 ReactElement 将类型放松为
ReactElement<ItemProps, string | JSXElementConstructor<any>>
ReactElement<ItemProps, string | JSXElementConstructor<any>>
, or more generally: ReactElement<ItemProps, string | JSXElementConstructor<any>>
,或更一般地说:
ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>>
ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>>
. ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>>
。
The issue: if I were to replace with any other component, there wouldn't be any explicit warning or error about the component being different.问题:如果我要替换任何其他组件,则不会有任何关于组件不同的明确警告或错误。 I am trying to instead narrow it such that only the
<Item />
component can be passed for the item={}
prop of <Parent />
.我试图缩小它的范围,以便只有
<Item />
组件可以传递给<Parent />
的item={}
道具。
In essence, what are some ways that can explicitly define a specific React component as a prop for a parent React component?本质上,有哪些方法可以显式地将特定的 React 组件定义为父 React 组件的 prop?
Because the Component returns JSX.Element
, And the JSX.Element
was extended from ReactElement
.因为 Component 返回
JSX.Element
,而JSX.Element
是从ReactElement
扩展而来的。
interface Element extends React.ReactElement<any, any> { }
And I think if you want to assert the component that receives from the parent Component, you can receive the complete component like this而且我认为如果你想断言从父组件接收的组件,你可以像这样接收完整的组件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.