何时使用 React.PropsWithChildren

When to use React.PropsWithChildren

在我看来是两个相似的设置,在一台机器上我被允许调用

<MyApp
        accountId={this.props.accountId}
        children={toggleButton} />

MyApp 有 class 签名

export interface IMyAppProps {
  accountId: string;
  dispatch: any;
}
    class MyApp extends React.Component<IMyAppProps, IMyAppState> {

在另一台机器上,运行 npm run-script build 失败

TypeScript build error TS2322: Type ' ... ' is not assignable to type ' ... '

Property 'children' does not exist on type 'IntrinsicAttributes & Pick<IMyAppProps, "accountId">'

两台机器上使用的版本 react-scripts-ts 4.0.8,typescript 3.4.5。

将 class 定义更改为此使其可以在两台机器上运行

class MyApp extends React.Component<React.PropsWithChildren<IMyAppProps>, IMyAppState> {

我不确定为什么它在一种设置中有效,而在另一种设置中无效。我什么时候将我的道具界面包装在 React.PropsWithChildren 中?

我最好的猜测是可以在 React 或与 React 相关的包的类型文件中找到更改。

我不知道为什么它在一台机器上运行,但在另一台机器上运行,但我认为这不是使用 children 属性.

的正确方法

而不是这个...

<MyApp
        accountId={this.props.accountId}
        children={toggleButton} />

...我认为children的目的是让你这样调用...

<MyApp accountId={this.props.accountId}>
  <ToggleButton/>
</MyApp>

...或类似的东西。

一个或多个子项——<ToggleButton/> 在我上面的例子中——可能是一个 React 元素,或者文本(一个文本节点),或者 undefined 如果没有子项,或者可能像 {toggleButton} 这样的表达式,其计算结果为其中一种子类型。

实际答案与您使用<MyApp children={...}还是<MyApp><Child /></MyApp>无关。不同之处在于,在第一个示例中 IMyAppProps 没有定义 children 属性,因此 TypeScript 会抱怨您不能那样使用它。当您将其包装在 WithChildren 中时,会向界面添加 children 属性。