React.memo 与typescript在react

IT技术 reactjs typescript
2021-05-11 03:34:15

我在 .tsx 文件(React typescript)中使用 React.memo()

现在我已经为 Props 声明了一个接口:

interface Props {
  type?: string;
}

我的组件看起来像:

const Component: React.SFC<Props> = props => {
  /// return something;
};

export default memo(Component);

现在因为 type 是一个可选的 prop,我打算只在某些时候使用它。

如果我使用我的组件,<Component type="something" />一切都很好。但是如果我使用它时<Component />出现错误-->

输入'{孩子:字符串;}' 与类型 'IntrinsicAttributes & Props' 没有共同的属性。

这似乎是一个非常荒谬的错误,因为我已经在代码沙箱上尝试过,并且一切正常。关于错误可能是什么的任何想法?

更新

如果我在界面中明确添加一个props,如

interface Props {
  type?: string;
  children?: ReactNode;
}

那么在这种情况下一切正常。这应该是隐含的,但根据错误将其视为

'{ 孩子:字符串;}'

有任何想法吗???

1个回答

我相信打字有错误。改变

function memo<P extends object>(
  Component: SFC<P>,
  propsAreEqual?: (
    prevProps: Readonly<PropsWithChildren<P>>,
    nextProps: Readonly<PropsWithChildren<P>>
  ) => boolean
): NamedExoticComponent<P>;

function memo<P extends object>(
  Component: SFC<P>,
  propsAreEqual?: (
    prevProps: Readonly<PropsWithChildren<P>>,
    nextProps: Readonly<PropsWithChildren<P>>
  ) => boolean
): NamedExoticComponent<PropsWithChildren<P>>;

解决问题

更新

嗯,实际上这不是一个错误。讨论

TLTR:您必须children在组件props类型中指定

type MyComponentProps {
  children: React.ReactNode;
}

阅读更多