原文连接: https://medium.com/@jrwebdev/...
高阶组件(HOCs)在React中是组件复用的一个强大工具。可是,常常有开发者在结合TypeScript使用中抱怨道很难去为其设置types。javascript
这边文章将会假设你已经具有了HOCs的基本知识,并会根据由浅入深的例子来向你展现如何去为其设置types。在本文中,高阶组件将会被分为两种基本模式,咱们将其命名为enhancers和injectors:html
请注意,本文中的示例并非最佳实践,本文主要只是展现如何在HOCs中设置types。java
咱们将从enhancers开始,由于它更容易去设置types。此模式的一个基本示例是一个向组件添加loading props的HOC,而且将其设置为true的时候展现loading图。下面是一个没有types的示例:react
const withLoading = Component => class WithLoading extends React.Component { render() { const { loading, ...props } = this.props; return loading ? <LoadingSpinner /> : <Component {...props} />; } };
而后是加上typesweb
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} />; } };
这里发生了一些事情,因此咱们将把它分解:typescript
interface WithLoadingProps { loading: boolean; }
在这里,声明一个props的interface,将会被添加到被包裹的组件上。redux
<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)。它们经过 & 组合在一块儿。app
const { loading, ...props } = this.props;
最后,咱们使用loading props有条件地显示加loading图或传递了本身props的组件:less
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是更常见的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,这意味着若是它们设置在生成的包裹组件上,则会收到编译错误:

结合这两种模式,咱们将在计数器示例的基础上,容许将最小和最大计数器值传递给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冲突。您能够将名称更改成不太通用的解决方案,但就解决方案而言,这不是一个很好的解决方案!