【问题标题】:Flow types for optional parameter in higher order React component高阶 React 组件中可选参数的流类型
【发布时间】:2019-07-21 16:23:26
【问题描述】:

我正在尝试使用 Flow 类型创建一个高阶组件,但在返回的组件类型上遇到了问题。

小例子:

/* @flow */

import React from 'react';

type Props = {
  name: string,
  what: number
}

const TestComponent = (props: Props) => null

function withDefaultClassname<Config: {}>(
  Component: React$AbstractComponent<Config, *>
): React$AbstractComponent<{...$Exact<Config>, name: string}, *> {
  return (props) => <Component {...props} className={props.className || 'default'} />;
}
const Wrapped2 = withDefaultClassname(TestComponent)

// $ExpectError - should complain about undefined props
const a = <Wrapped2 />

在上面的示例中,如果 className 属性不存在,则高阶组件设置它,否则使用提供的属性。因此,我尝试将高阶组件的返回类型设置为将className 设置为可选道具。然而,这似乎会导致 Flow 不再强制执行原本需要的 props 的问题。有没有更好的方法来做到这一点?

Flow 文档talks about injecting props,但这涉及使用$Diff 实用程序类型。我想指出这里的返回类型确实包含 className 作为可选属性,这使得 $Diff 实用程序类型在这种情况下没有帮助。

【问题讨论】:

    标签: javascript reactjs flowtype


    【解决方案1】:

    Config &amp; {className?: string} 好像是to works correctly

    function withDefaultClassname<Config: {}>(
          Component: React$AbstractComponent<Config, *>
        ): React$AbstractComponent<Config & {className?: string}, *> {
          return (props) => <Component className={props.className || 'default'} {...props} />;
        }
    

    merging exact types 最好使用扩展运算符。

    【讨论】:

      猜你喜欢
      • 2019-07-25
      • 2021-12-30
      • 2022-01-23
      • 2019-12-15
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 2012-11-21
      • 2017-10-12
      相关资源
      最近更新 更多