【问题标题】:Passing generics to a component wrapped in a HOC将泛型传递给封装在 HOC 中的组件
【发布时间】:2019-09-13 12:19:16
【问题描述】:

我有一个 ApolloGraphQL 查询组件的实现。

当使用 Apollo 客户端查询组件时,类型可以这样传递:

import * as ApolloTypes from './__generated__/GetSubreddit';

 <Query<ApolloTypes.GetSubreddit, ApolloTypes.GetSubredditVariables>
      query={GET_SUBREDDIT}
      variables={{ name: selectedSubreddit }}
    >
...
</Query>

我有自己的组件,它实现了 Apollo Query 组件。除其他外,它为每个查询添加了一些标题。我希望能够以与普通查询组件相同的方式传递它的类型,这很容易在没有来自“react-redux”的connect 高阶组件的情况下完成。我不知道如何通过 HOC 传递泛型。有什么建议吗?

const GraphqlQuery = <T, TVariables = OperationVariables>(props: PropsType) => {
  const { query, variables, children, user, ...rest } = props;
  if (!user) return null;

  return (
    <Query<T, TVariables>
      query={query}
      variables={variables}
      context={{
        headers: {
          "X-User-Id": user.id,
        },
      }}
      {...rest}
    >
    ...
    </Query>
  );
};


const mapStateToProps = ({ user }: { user: IUserState }) => ({
  user,
});
export default connect(
  mapStateToProps,
  {}
)(GraphqlQuery);

【问题讨论】:

    标签: reactjs typescript generics higher-order-functions


    【解决方案1】:

    我能想到的有 2 个选项可以帮助您实现这一目标:

    1. Cast the export:

    在您的情况下,这可能有点棘手,但只要 HOC 不需要任何道具,这样的事情就可以工作。如果是,则必须更改要转换为的类型。

    export default connect(
      mapStateToProps,
      {}
    )(GraphqlQuery) as typeof GraphqlQuery
    
    1. 工厂
    export const createGraphqlQuery = <T, TVariables = OperationVariables>() => {
      const GraphqlQuery = (props: PropsType) => {
        const { query, variables, children, user, ...rest } = props;
        if (!user) return null;
    
        return (
          <Query<T, TVariables>
            query={query}
            variables={variables}
            context={{
              headers: {
                "X-User-Id": user.id,
              },
            }}
            {...rest}
          >
          ...
          </Query>
        );
      };
    
    
      const mapStateToProps = ({ user }: { user: IUserState }) => ({
        user,
      });
      return connect(
        mapStateToProps,
        {}
      )(GraphqlQuery)
    };
    

    用法:

    const GraphqlQuery = createGraphqlQuery<{}, {}>();
    
    <GraphqlQuery ... />
    
    

    每个人都有一定的权衡。

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 2020-01-26
      • 2016-02-12
      相关资源
      最近更新 更多