简体   繁体   English

React.memo与反应中的打字稿

[英]React.memo with typescript in react

I am using React.memo() in a .tsx file(React typescript) 我在.tsx文件中使用React.memo()(React typescript)

Now I have declared an interface for Props as: 现在我已经为Props声明了一个接口:

interface Props {
  type?: string;
}

My component looks like: 我的组件看起来像:

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

export default memo(Component);

Now since type is an optional prop I intend to use it only sometimes. 现在因为type是一个可选的prop我打算有时只使用它。

If I use my component as <Component type="something" /> everything is okay. 如果我使用我的组件作为<Component type="something" />一切都没问题。 But if I use it as <Component /> I get the error --> 但如果我用它作为<Component />我得到错误 - >

Type '{ children: string; 输入'{children:string; }' has no properties in common with type 'IntrinsicAttributes & Props'. }'没有与'IntrinsicAttributes&Props'类型相同的属性。

This seems to be a very absurd error as I have tried this on Code sandbox and everything works fine. 这似乎是一个非常荒谬的错误,因为我在Code沙盒上尝试了这一点,一切正常。 Any ideas about what the error could be? 关于错误可能是什么的任何想法?

UPDATE UPDATE

If I explicitly add a prop in interface like 如果我在界面中明确添加道具就像

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

then in that case everything works fine. 那么在那种情况下一切正常。 This is supposed to be implicit but acc to the error its taking as 这应该是隐含的,但要考虑到它所带来的错误

'{ children: string; '{children:string; }' }”

Any ideas??? 有任何想法吗???

I believe there is an error in typings. 我相信打字有一个错误。 Changing 更改

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

to

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

fixes the issue 解决了这个问题

UPDATE UPDATE

Well, actually it is not a bug. 嗯,实际上它不是一个bug。 See discussion . 讨论

TLTR: You have to specify children in component props type. TLTR:您必须在组件道具类型中指定children

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM