reactjs - 如何键入一个接受另一个组件作为 Prop 的 React 组件,以及该组件的所有 Prop ?

标签 reactjs typescript emotion

我有一个 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 .正确的类型是什么,这样的事情甚至可能吗?

最佳答案

您需要的领带是ComponentTypeElementType .

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/

相关文章:

javascript - JavaScript 中的下划线 "_"是什么?

javascript - 在生产构建中为代理生成未捕获的类型错误

javascript - 使用 `Status Code:400 Bad Request` 类型的数据调用 Microsoft Azure Emotion API 时获取 `Content-Type:application/octet-stream`

Material-UI Table/XGrid - 如何为每个单元格设置不同的颜色

reactjs - 在 Github 页面上使用react : gh-pages package not working

Reactjs-Popup:无法读取未定义的属性(读取 'forwardRef' )

javascript - 如何在 react 中设置类属性的值

javascript - TypeScript - 一次又一次调用 API 端点,直到得到所需的结果 - 递归还是循环?

javascript - TypeScript 在对象中查找键时出现问题

laravel - npm run watch/hot 仅在第一次运行时成功