如何使用flow为HoC编写类型定义

时间:2017-03-31 13:17:15

标签: reactjs flowtype higher-order-components

我试图为HoC写一个流类型,它将返回一个组件并为它添加一个prop isVisible

type VisibleProps = {isVisible: boolean}

const VisibleComp = <P, S>(Component: Class<React.Component<void, P, S>>)
  : Class<React.Component<void, P&VisibleProps, S> => 
  class WrappedComponent extends React.Component<void, P&VisibleProps, S> {
      render() {
          return <Component {...this.props} isVisible={true} />
      }
  }

我尝试了几件事没有成功:(

1 个答案:

答案 0 :(得分:0)

深入研究流程问题,我发现这个问题解决了我的问题 https://github.com/facebook/flow/issues/3241

希望它有所帮助。

// @flow
import React from 'react';

type Visible = {isVisible: boolean}
type WrappedProps<P,Visible> = P & Visible  

const injectVisible = <P: Object>(
  Component: Class<React.Component<*, WrappedProps<P, Visible>, *>>
) => class VisibleHoC extends React.Component<*, P, Visible> {
      state: Visible
      render() {
          return <Component {...this.props} isVisible={true} />
      }
  }

class Component extends React.Component {
  props: Visible
  render() {
    return <div> {this.props.isVisible ? 'visible' : 'hidden'}</div>
  }
}

const VisibleComponent = injectVisible(Component)