简体   繁体   English

将 Children 道具传递给 React Memo 组件

[英]Pass Children prop to React Memo component

I am currently in the process of optimising a number of React SFC components with the use of React.memo .我目前正在使用React.memo优化一些 React SFC 组件。

Most of these components have children.这些组件中的大多数都有子组件。 The project also uses TypeScript.该项目还使用了TypeScript。

I was starting to get the impression that memo components did not support children as I was presented with the following error message every time there was an error:我开始觉得备忘录组件不支持子组件,因为每次出现错误时我都会收到以下错误消息:

Property 'children' does not exist on type 'IntrinsicAttributes & object'类型“IntrinsicAttributes & object”上不存在属性“children”

It turns out this only applies when I provide a Props type to the component.事实证明,这只适用于我为组件提供 Props 类型的情况。 Eg例如

const MyComponent: React.SFC<PropType>

If I remove the prop type (as below) then the error does not occur.如果我删除道具类型(如下所示),则不会发生错误。

const MyComponent: React.SFC

Of course, I need the prop type in most every case.当然,在大多数情况下,我都需要 prop 类型。

I have setup a Code Sandbox that emulates the issue:我已经设置了一个模拟问题的代码沙箱:

https://codesandbox.io/s/cool-keldysh-urddu?fontsize=14&hidenavigation=1&theme=dark https://codesandbox.io/s/cool-keldysh-urddu?fontsize=14&hidenavigation=1&theme=dark

tl;dr: why do React.memo components not accept the child prop when a type has been provided for the component props? tl;dr:为什么 React.memo 组件在为组件道具提供了类型时不接受子道具?

This appears to be an issue with the React.memo typings, it doesn't automatically pass through children props.这似乎是React.memo的问题,它不会自动通过 children 道具。 There's a discussion on the DefinitelyTyped repo.有一个关于绝对类型回购的 讨论

For now, you can manually specify the children prop:现在,您可以手动指定children道具:

type ChildProps = {
  name: string;
  children: React.ReactNode;
};

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

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