我有一个 React 组件 <Wrapper>
我可以使用如下:
// Assuming Link is a component that takes a `to` prop: <Link to="/somewhere">label</Link>
<Wrapped as={Link} to="/somewhere">label</Wrapped>
如果没有
as
prop 被传递,它将假设一个 <a>
.但是如果一个组件被传递给 as
,对该组件有效的所有 Prop 现在也应该是 Wrapped
的有效 Prop 。 .有没有办法在 TypeScript 中输入这个?我目前正在考虑以下方面:
type Props<El extends JSX.Element = React.ReactHTMLElement<HTMLAnchorElement>> = { as: El } & React.ComponentProps<El>;
const Wrapped: React.FC<Props> = (props) => /* ... */;
但是,我不确定是否
JSX.Element
和/或 React.ComponentProps
是这里的相关类型,这不会编译,因为 El
不能传给ComponentProps
.正确的类型是什么,这样的事情甚至可能吗?
最佳答案
您需要的领带是ComponentType
和 ElementType
.
import React, { ComponentType, ElementType, ReactNode } from 'react';
type WrappedProps <P = {}> = {
as?: ComponentType<P> | ElementType
} & P
function Wrapped<P = {}>({ as: Component = 'a', ...props }: WrappedProps<P>) {
return (
<Component {...props} />
);
}
有了它,你就可以做到:
interface LinkProps {
to: string,
children: ReactNode,
}
function Link({ to, children }: LinkProps) {
return (
<a href={to}>{children}</a>
);
}
function App() {
return (
<div>
<Wrapped<LinkProps> as={Link} to="/foo">Something</Wrapped>
<Wrapped as="div" style={{ margin: 10 }} />
<Wrapped />
</div>
);
}
关于reactjs - 如何键入一个接受另一个组件作为 Prop 的 React 组件,以及该组件的所有 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61148557/