【译】TypeScript中的React高阶组件

9,245 阅读5分钟

原文链接:medium.com/@jrwebdev/r…

高阶组件(HOCs)在React中是组件复用的一个强大工具。但是,经常有开发者在结合TypeScript使用中抱怨道很难去为其设置types。

这边文章将会假设你已经具备了HOCs的基本知识,并会根据由浅入深的例子来向你展示如何去为其设置types。在本文中,高阶组件将会被分为两种基本模式,我们将其命名为enhancersinjectors

  • enhancers:用附加的功能/props来包裹组件。
  • injectors:向组件注入props。

请注意,本文中的示例并不是最佳实践,本文主要只是展示如何在HOCs中设置types。


Enhancers

我们将从enhancers开始,因为它更容易去设置types。此模式的一个基本示例是一个向组件添加loading props的HOC,并且将其设置为true的时候展示loading图。下面是一个没有types的示例:

const withLoading = Component =>
  class WithLoading extends React.Component {
    render() {
      const { loading, ...props } = this.props;
      return loading ? <LoadingSpinner /> : <Component {...props} />;
    }
  };

然后是加上types

interface WithLoadingProps {
  loading: boolean;
}

const withLoading = <P extends object>(Component: React.ComponentType<P>) =>
  class WithLoading extends React.Component<P & WithLoadingProps> {
    render() {
      const { loading, ...props } = this.props;
      return loading ? <LoadingSpinner /> : <Component {...props as P} />;
    }
  };

这里发生了一些事情,所以我们将把它分解:

interface WithLoadingProps {
  loading: boolean;
}

在这里,声明一个props的interface,将会被添加到被包裹的组件上。

<P extends object>(Component: React.ComponentType<P>)

这里我们使用泛型:P表示传递到HOC的组件的props。React.ComponentType<P>React.FunctionComponent<P> | React.ClassComponent<P>的别名,表示传递到HOC的组件可以是类组件或者是函数组件。

class WithLoading extends React.Component<P & WithLoadingProps>

在这里,我们定义从HOC返回的组件,并指定该组件将包括传入组件的props(P)和HOC的props(WithLoadingProps)。它们通过 & 组合在一起。

const { loading, ...props } = this.props;

最后,我们使用loading props有条件地显示加loading图或传递了自己props的组件:

return loading ? <LoadingSpinner /> : <Component {...props as P} />;

注意:由于typescript中可能存在的bug,因此从typescript v3.2开始,这里需要类型转换(props as p)。

我们的withloading HOC也可以重写以返回函数组件而不是类:

const withLoading = <P extends object>(
  Component: React.ComponentType<P>
): React.FC<P & WithLoadingProps> => ({
  loading,
  ...props
}: WithLoadingProps) =>
  loading ? <LoadingSpinner /> : <Component {...props as P} />;

这里,我们对对象rest/spread也有同样的问题,因此通过设置显式的返回类型React.FC<P & WithLoadingProps>来解决这个问题,但只能在无状态功能组件中使用WithLoadingProps。

注意:React.FC是React.FunctionComponent的缩写。在早期版本的@types/react中,是React.SFC或React.StatelessFunctionalComponent。

Injectors

injectors是更常见的HOC形式,但更难为其设置类型。除了向组件中注入props外,在大多数情况下,当包裹好后,它们也会移除注入的props,这样它们就不能再从外部设置了。react redux的connect就是是injector HOC的一个例子,但是在本文中,我们将使用一个更简单的例子,它注入一个计数器值并回调以增加和减少该值:

import { Subtract } from 'utility-types';

export interface InjectedCounterProps {
  value: number;
  onIncrement(): void;
  onDecrement(): void;
}

interface MakeCounterState {
  value: number;
}

const makeCounter = <P extends InjectedCounterProps>(
  Component: React.ComponentType<P>
) =>
  class MakeCounter extends React.Component<
    Subtract<P, InjectedCounterProps>,
    MakeCounterState
  > {
    state: MakeCounterState = {
      value: 0,
    };

    increment = () => {
      this.setState(prevState => ({
        value: prevState.value + 1,
      }));
    };

    decrement = () => {
      this.setState(prevState => ({
        value: prevState.value - 1,
      }));
    };

    render() {
      return (
        <Component
          {...this.props as P}
          value={this.state.value}
          onIncrement={this.increment}
          onDecrement={this.decrement}
        />
      );
    }
  };

这里有几个关键区别:

export interface InjectedCounterProps {  
  value: number;  
  onIncrement(): void;  
  onDecrement(): void;
}

我们给将要注入到组件的props声明一个interface,该接口将被导出,以便这些props可由被HOC包裹的组件使用:

import makeCounter, { InjectedCounterProps } from './makeCounter';

interface CounterProps extends InjectedCounterProps {
  style?: React.CSSProperties;
}

const Counter = (props: CounterProps) => (
  <div style={props.style}>
    <button onClick={props.onDecrement}> - </button>
    {props.value}
    <button onClick={props.onIncrement}> + </button>
  </div>
);

export default makeCounter(Counter);
<P extends InjectedCounterProps>(Component: React.ComponentType<P>)

我们再次使用泛型,但是这次,你要确保传入到HOC的组件包含注入到其中的props,否则,你将收到一个编译错误。

class MakeCounter extends React.Component<
  Subtract<P, InjectedCounterProps>,    
  MakeCounterState  
>

HOC返回的组件使用Piotrek Witek’s的utility-types包中的subtract,它将从传入组件的props中减去注入的props,这意味着如果它们设置在生成的包裹组件上,则会收到编译错误:

TypeScript compilation error when attempting to set value on the wrapped component

Enhance + Inject

结合这两种模式,我们将在计数器示例的基础上,允许将最小和最大计数器值传递给HOC,而HOC又被它截取并使用,而不将它们传递给组件:

export interface InjectedCounterProps {
  value: number;
  onIncrement(): void;
  onDecrement(): void;
}

interface MakeCounterProps {
  minValue?: number;
  maxValue?: number;
}

interface MakeCounterState {
  value: number;
}

const makeCounter = <P extends InjectedCounterProps>(
  Component: React.ComponentType<P>
) =>
  class MakeCounter extends React.Component<
    Subtract<P, InjectedCounterProps> & MakeCounterProps,
    MakeCounterState
  > {
    state: MakeCounterState = {
      value: 0,
    };

    increment = () => {
      this.setState(prevState => ({
        value:
          prevState.value === this.props.maxValue
            ? prevState.value
            : prevState.value + 1,
      }));
    };

    decrement = () => {
      this.setState(prevState => ({
        value:
          prevState.value === this.props.minValue
            ? prevState.value
            : prevState.value - 1,
      }));
    };

    render() {
      const { minValue, maxValue, ...props } = this.props;
      return (
        <Component
          {...props as P}
          value={this.state.value}
          onIncrement={this.increment}
          onDecrement={this.decrement}
        />
      );
    }
  };

这里,Subtract与types交集相结合,将组件自身的props与HOCs自身的props相结合,减去注入组件的props:

Subtract<P, InjectedCounterProps> & MakeCounterProps

除此之外,与其他两种模式相比,没有真正的差异需要强调,但是这个示例确实带来了一些高阶组件的问题。这些并不是真正特定于typescript的,但值得详细说明,以便我们可以讨论如何使用typescript来解决这些问题。

首先,MinValue和MaxValue被HOC拦截,而不是传递给组件。但是,你也许希望它们是这样的,这样你就可以基于这些值禁用递增/递减按钮,或者向用户显示一条消息。如果用HOC,你也可以简单地修改它来注入这些值,但是如果你没有(例如,它来自一个NPM包),这就将会是一个问题。

其次,由HOC注入的prop有一个非常通用的名称;如果要将其用于其他目的,或者如果要从多个HOC注入prop,则此名称可能与其他注入的prop冲突。您可以将名称更改为不太通用的解决方案,但就解决方案而言,这不是一个很好的解决方案!