React:如何正确输入HOC组件?

时间:2019-05-13 17:41:54

标签: reactjs flowtype high-order-component

我搜索了建议,但找不到任何答案。 我基本上认为我可以按如下所示正确键入HOC:

这是我目前的组件:

// @flow
import React, { Component } from 'react';
import moment from 'moment';
import type { ApolloClient } from 'apollo-client';

import { convertDatesToISO } from 'components/Calendar/utils';


type Props = {
  client: ApolloClient<any>,
  location: {
    search: string,
  },
};

type SelectedDates = {
  startOn: moment,
  endOn: moment,
};



const withInitialSelectedDates = (WrappedComponent: Component<Props>): Component => {
  return class extends Component<Props> {
    initialSelectedDates: ?SelectedDates;

    initialSelectedDatesFromQueryString(): ?SelectedDates {
      const searchString = this.props.location.search;
      const searchParams = new URLSearchParams(searchString);
      const startOn = moment.utc(searchParams.get('start_date'));
      const endOn = moment.utc(searchParams.get('end_date'));

      if (!startOn.isValid() || !endOn.isValid()) return null;
      if (startOn < moment.utc().startOf('day')) return null;
      if (endOn < startOn) return null;

      return { startOn, endOn };
    }

    setInitialSelectedDatesOnGraphQLClient(): void {
      if (this.initialSelectedDates == null) return;

      this.props.client.writeData({
        data: {
          selectedDates: convertDatesToISO([this.initialSelectedDates]),
        },
      });
    }

    componentDidMount(): void {
      this.initialSelectedDates = this.initialSelectedDatesFromQueryString();
      this.setInitialSelectedDatesOnGraphQLClient();
    }

    render(): React.Element {
      return (
        <WrappedComponent
          initialSelectedDates={this.initialSelectedDates}
          {...this.props}
        />
      );
    }
  };
};

export default withInitialSelectedDates;

我想我可以改变:

const withInitialSelectedDates = (WrappedComponent: Component<Props>): Component => {

对此:

const withInitialSelectedDates = <PassedProps: {} & Props>(WrappedComponent: ComponentType<PassedProps>): ComponentType<PassedProps> => {

这将需要导入ComponentType。我的问题是我应该在哪里更改当前代码并添加PassedProps?

1 个答案:

答案 0 :(得分:0)

您将要遵循HOC Flow文档的"Injecting Props" section中的示例。一个示例实现可能看起来像

OverwriteSucessForm f4 = new OverwriteSucessForm();

f4.Show(/*will this accept anything other than "this"?*/);

f4.BringToFront();

f4.TopMost = true;

Try Flow