【问题标题】:Type '{ children: ReactNode; }' has no properties in common with type 'IntrinsicAttributes'输入'{孩子:ReactNode; }' 与类型 'IntrinsicAttributes' 没有共同的属性
【发布时间】:2021-07-02 19:37:27
【问题描述】:

我确实知道这里有几个话题谈到了这个错误,但没有一个对我有帮助。

我正在尝试创建一个可重用的 Typography 组件,如下所示:

import React from 'react'
import type { TypographyProps } from './types';

export const variantsMapping = {
  h1: "h1",
  h2: "h2",
  h3: "h3",
  h4: "h4",
  h5: "h5",
  h6: "h6",
  body: "p",
};

const Typography: React.FC<TypographyProps> = ({ children, color, size, variant, ...props }) => {
  const Component = variant ? variantsMapping[variant] : "p";
  return (
    <Component>
      {children}
    </Component>
  )
}

export default Typography;

但我在&lt;Component&gt; 中收到此错误:

我该如何解决?这是我的 TypographyProps:

import React from 'react';
import { variantsMapping } from './Typography';

export type TypographyProps = {
  children: React.ReactNode;
  size?: string;
  color?: string;
  variant?: keyof typeof variantsMapping;
};

我尝试将孩子更改为任何但我没有工作。我也尝试过使用来自 React 类型的 PropsWithChildren,但没有。

我错过了什么?

【问题讨论】:

    标签: reactjs typescript next.js


    【解决方案1】:

    您必须声明您的 variantsMapping as const 以防止将其类型扩大到 { [x: string]: string }。那么打字稿就可以猜到你的variangMapping[variant] | "p"keyof JSX.IntrinsicElements的一个子集:

    import React from 'react'
    import type { TypographyProps } from './types';
    
    export const variantsMapping = {
      h1: "h1",
      h2: "h2",
      h3: "h3",
      h4: "h4",
      h5: "h5",
      h6: "h6",
      body: "p",
    } as const; // prevents type widening
    
    const Typography: React.FC<TypographyProps> = ({ children, color, size, variant, ...props }) => {
      const Component = variant ? variantsMapping[variant] : "p";
      return (
        <Component>
          {children}
        </Component>
      )
    }
    
    export default Typography;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 2022-07-05
      • 2023-01-05
      • 2021-06-29
      • 2022-08-17
      • 2022-09-23
      • 2022-10-17
      相关资源
      最近更新 更多