声明由第三方组件添加的道具的流量类型



我正在使用victory j在React中创建图表。胜利有一个称为<VictoryBar>的组件,该组件可以采用一个称为labelComponent的道具,我正在通过<BarLabel/>

示例:

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

问题是我正在使用Flow进行类型检查,而VictoryBar将道具添加到<BarLabel/>。这是我的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>
  );
}

流文档给出了指定高订单功能道具的示例,但对我的方案无济于事。如何通过VictoryBar

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

到目前为止,胜利还没有定义任何官方流动类型,因此一旦安装了此模块,就需要创建一个存根以删除您使用的胜利版本的流动错误。可以使用flow-typed create-stub命令,例如:

flow-typed create-stub victory@^30.3.0

这将生成将流类型声明为./flow-typed目录的文件。这应该消除您与胜利有关的任何流动错误。您可以了解有关流文档中声明流量类型的更多信息。

对于第三方库,始终最好查看该流类型是否已经存在,此时您可以安装它们。这可以使用flow-typed install命令,例如

flow-typed install bson@^1.0.0

对于现有流类型,您还可以将现有定义的声明复制和粘贴到项目的./flow-typed目录中。

最新更新