【问题标题】:Can I type React Children using Typescript?我可以使用 Typescript 输入 React Children 吗?
【发布时间】:2022-01-15 03:28:01
【问题描述】:

我正在使用 styled-components 构建消息卡组件。我试图让它有尽可能少的逻辑和尽可能少的道具,所以我使用 CSS 来设置任何 <p><svg> 元素的样式,这些元素作为子元素传入,如下所示:

我也在使用 typescript,我想确保作为子元素传入的唯一元素类型至少是 1 个段落元素和 1 个 SVG 元素?

例如这样的:

type = MessageCardProps = {
  children: [ JSXSVGElement?, JSXParagraphElement, JSXParagraphElement]
}

【问题讨论】:

    标签: reactjs typescript types children react-typescript


    【解决方案1】:

    目前无法按照您想要的方式实现它。不幸的是,ReactElement 放松了类型检查,如下所述:How do I restrict the type of React Children in TypeScript, using the newly added support in TypeScript 2.3?

    毕竟Reacts Composition 使用道具通过appropriate types 将其传递给您的组件:

    import { ComponentPropsWithoutRef, PropsWithChildren } from "react";
    
    type MessageCardProps = PropsWithChildren<{
      icon: ComponentPropsWithoutRef<"svg">;
      title: string;
    }>;
    
    function MessageCard({ icon, title, children }: MessageCardProps) {
      return <div>{icon}{title}{children}</div>;
    }
    
    export default function App() {
      return (
        <MessageCard icon={<svg></svg>} title="title">
          message
        </MessageCard>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-20
      • 1970-01-01
      • 2017-09-14
      • 2012-12-17
      • 1970-01-01
      • 2014-09-14
      • 2022-11-17
      • 2019-12-24
      • 2016-06-14
      相关资源
      最近更新 更多