[英]Typescript: Property 'type' does not exist on type 'string'
I'm trying to do a React component that has subcomponents within.我正在尝试做一个包含子组件的 React 组件。 I've been reading this article to achive so.我一直在阅读这篇文章来实现这一目标。
The idea is to create a Modal which has Modal.Header, Modal.Body and Modal.Footer.这个想法是创建一个具有 Modal.Header、Modal.Body 和 Modal.Footer 的模态框。
Although I could create the component and it works fine, I'm having a typing error.虽然我可以创建组件并且它工作正常,但我遇到了输入错误。
The problem is in a function called getChildrenOnDisplayName.问题出在一个名为 getChildrenOnDisplayName 的 function 中。 I use the function in the main component to get the subcomponents and render them.我在主组件中使用 function 来获取子组件并渲染它们。
interface ModalProps {
children: React.ReactNode,
open?: boolean,
closeFunc?: () => void,
preventCloseFromOutside?: boolean,
hideCloseButton?: boolean,
}
const Modal = ({ children, open, closeFunc, preventCloseFromOutside = false, hideCloseButton = false }: ModalProps) => {
const header = useMemo(() => getChildrenOnDisplayName(children, "Header"), [children]);
const body = useMemo(() => getChildrenOnDisplayName(children, "Body"), [children]);
const footer = useMemo(()=> getChildrenOnDisplayName(children, "Footer"), [children]);
return (
<>
<div className='header'>{header && header}</div>
<div className='body'>{body && body}</div>
<div className='footer'>{footer && footer}</div>
<style jsx>
{` styles...`}
</style>
</>
)
}
The function where I get the error:我收到错误的 function:
const getChildrenOnDisplayName = (children: React.ReactNode, displayName: string) => {
return React.Children.map(children, (child) =>
child?.type.displayName === displayName ? child : null
^^^^
)
}
The typing error: "Property 'type' does not exist on type 'string | number | boolean | ReactElement<any, string | JSXElementConstructor> | ReactFragment | ReactPortal'. Property 'type' does not exist on type 'string'."输入错误:“属性‘type’在类型‘string | number | boolean | ReactElement<any, string | JSXElementConstructor> | ReactFragment | ReactPortal’上不存在。属性‘type’在类型‘string’上不存在。”
How could I type it?我怎么能打字?
Thanks in advance!提前致谢!
You will probably have to use the typeof operator to isolate the native types like:您可能必须使用 typeof 运算符来隔离本机类型,例如:
if(typeof child === "string") {
// string
} else if(typeof child === "boolean") {
// bool
} else if( .. etc ..) {
// other types
} else {
// finally a react element
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.