何时使用 React.PropsWithChildren

Tho*_*rge 11 typescript reactjs react-props

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

<MyApp
        accountId={this.props.accountId}
        children={toggleButton} />
Run Code Online (Sandbox Code Playgroud)

MyApp 有类签名的地方

export interface IMyAppProps {
  accountId: string;
  dispatch: any;
}
    class MyApp extends React.Component<IMyAppProps, IMyAppState> {
Run Code Online (Sandbox Code Playgroud)

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

TypeScript 构建错误 TS2322:类型“...”不可分配给类型“...”

'IntrinsicAttributes & Pick<IMyAppProps, "accountId">' 类型不存在属性 'children'

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

将类定义更改为此使其在两台机器上都可以使用

class MyApp extends React.Component<React.PropsWithChildren<IMyAppProps>, IMyAppState> {
Run Code Online (Sandbox Code Playgroud)

我不确定为什么它适用于一种设置而不适用于另一种设置。我什么时候把我的 props 接口包装在里面React.PropsWithChildren

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

Chr*_*isW 6

我不知道为什么它可以在一台机器上工作,而在另一台机器上却不能,但我认为这不是使用该children属性的正确方法。

而不是这个...

<MyApp
        accountId={this.props.accountId}
        children={toggleButton} />
Run Code Online (Sandbox Code Playgroud)

......我想目的children是让你这样称呼......

<MyApp accountId={this.props.accountId}>
  <ToggleButton/>
</MyApp>
Run Code Online (Sandbox Code Playgroud)

... 或类似的东西。

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