【问题标题】:Declare Flow Types For Props Added By 3rd Party Component为由 3rd 方组件添加的道具声明流类型
【发布时间】:2017-03-15 18:51:17
【问题描述】:

我正在使用 Victory JS 在 React 中创建图表。 Victory 有一个名为 <VictoryBar> 的组件,它可以使用一个名为 labelComponent 的道具,我正在传递 <BarLabel/>

例子:

<VictoryBar
  labelComponent={<BarLabel/>}
/>

问题是我使用 Flow 进行类型检查,VictoryBar 将 props 添加到 &lt;BarLabel/&gt;。这是我的 BarLabel 道具和组件本身的类型。我在评论中解释了问题。

type BarLabelProps = {
  style?: Object,
  x?: number,
  y0?: number,

  // The problem lies here. When datum is optional I get the flow error
  // that props.datum.name is invalid because .name cannot be accessed from a 
  // possibly null value. When it is required (no question mark) I get an error 
  // because when I pass the component to <VictoryBar /> it does not contain
  // the prop datum until VictoryBar does it's thing. 
  datum?: Object,
};

function BarLabel(props: BarLabelProps) {
  return (
    <text
      textAnchor="middle"
      style={props.style}
      x={props.x + 70}
      y={props.y0 + 15}
    >
      <tspan style={props.style}>
        {props.datum.name}
      </tspan>
    </text>
  );
}

流程文档提供了一个在高阶函数上指定道具的示例,但对我的场景没有帮助。 如何告诉 flow 这些道具是通过VictoryBar 添加的?

【问题讨论】:

  • 这是一个有趣的问题。我对 React 和 Flow 的特殊情况不是很有经验,但我认为目前没有办法对此进行建模。
  • @Pizza-r0b,你能想为此抛出一个 repro-repo/codesandbox 吗?我想帮忙,但我有点懒,不想设置整个事情

标签: reactjs flowtype


【解决方案1】:

要在您的项目中支持第三方库的流类型,您可以使用flow-typed 模块。他们的安装说明说要全局安装,例如yarn global add flow-typednpm install -g flow-typed

到目前为止,Victory doesn't have any official Flow types defined 因此,一旦您安装了此模块,您将需要创建一个存根来删除您正在使用的 Victory 版本的 Flow 错误。这可以通过flow-typed create-stub 命令完成,例如:

flow-typed create-stub victory@^30.3.0

这将在./flow-typed 目录中生成声明流类型的文件。这应该会消除您与 Victory 相关的任何 Flow 错误。您可以了解有关声明流类型的更多信息in the Flow docs

对于一般的第三方库,最好查看 Flow 类型是否已经存在,此时您可以安装它们。这可以通过flow-typed install 命令来完成,例如

flow-typed install bson@^1.0.0

对于现有的 Flow 类型,您还可以将声明从 the existing definitions 复制并粘贴到项目的 ./flow-typed 目录中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-11
    • 2018-04-04
    • 1970-01-01
    • 2018-06-06
    • 2020-10-28
    • 1970-01-01
    • 2023-01-15
    • 1970-01-01
    相关资源
    最近更新 更多