【问题标题】:FlowType - Infer Generic Type on React ComponentFlowType - 在 React 组件上推断通用类型
【发布时间】:2018-03-16 14:18:23
【问题描述】:

我有以下组件

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

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

【问题讨论】:

  • 你能提供一个 flow.org/try 链接吗?我认为如果我们有更多的背景信息,我们可以更好地帮助你。 ??????
  • @MichaelDeBoey example
  • /订阅......

标签: reactjs generics jsx type-inference flowtype


【解决方案1】:

您的示例不起作用,因为在其中您将手风琴的状态初始化为字符串。

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

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

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

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

【讨论】:

    猜你喜欢
    • 2017-04-15
    • 2017-03-26
    • 1970-01-01
    • 2018-01-13
    • 2021-11-19
    • 2022-01-26
    • 2021-07-01
    • 2014-05-20
    • 1970-01-01
    相关资源
    最近更新 更多