reactjs - FlowType - 推断 React 组件的通用类型

标签 reactjs generics jsx type-inference flowtype

我有以下组件

type PropTypes<T> = {
  items: T[],
  header: (item: T) => React.Element<*>,
  body: (item: T) => React.Element<*>,
}
type StateTypes<T> = {
  expandItem: ?T,
};

export default class Accordian<T> extends React.Component {
  props: PropTypes<T>;
  state: StateTypes<T>;
  setExpandItem: (expandItem: ?T) => void;

  constructor(props: PropTypes<T>) {
    super(props);
    ...
  }
}

我真的很希望它从 items 推断出 header 的参数具有相同的类型。相反,当我用

初始化组件时
<Accordian
    items={list}
    header={listItem => ...}
/>

我收到:

-^ React element `Accordian`
20: export default class Accordian<T> extends React.Component {
                                   ^ T. This type is incompatible with. 
See: src/App/components/Accordian/index.js:20
19:   banks: GenericBank[],
             ^^^^^^^^^^^ object type

我找到了 similar question对于 TypeScript,但我想知道是否可以推断 FlowType 中 React 元素的 props 的泛型类型?

最佳答案

您的示例不起作用,因为您正在将 Accordion 的状态初始化为字符串。

class Accordian<T> extends React.Component<PropTypes<T>, StateTypes<T> {
    state = {
      expandItem: '1'
    };
}

string 与类型 T 不兼容,因为 T 可能并不总是 string。 Accordion 类在使用之前无法知道 T 是什么类型,因此它需要处理所有可能的类型。

如果删除此状态初始值设定项,代码就可以正常工作。如果您想将初始扩展项设置为 items 数组 Prop 中的第一项,您也可以在类构造函数中执行此操作

class Accordian<T> extends React.Component<PropTypes<T>, StateTypes<T>> {
  constructor(props) {
    super(props)
    this.setState({
      expandItem: this.props.items[0]
    });
  }
}

关于reactjs - FlowType - 推断 React 组件的通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46577548/

相关文章:

scala - 为什么 deriveHCons 的签名在 Symbol 是最终类时声明 `HK <: Symbol`

javascript - 文本节点不能作为 <table> [ReactJS] 的子节点出现

android - 如何在 React Native 中显示服务器对 HTTP 错误的响应

reactjs - Autosizer 制作高度和宽度为 0 的 div

reactjs - 具有自定义根和基本组件的 React Router

java - 泛型类的数组

generics - 类型参数: expected 1 but found 0的数量错误

javascript - 在 React 中使用 map 渲染元素

javascript - 获取 props in action -> reducer -> 自定义函数

javascript - 如何使用正则表达式来约束 ReactJS 路由