3

所以我目前正在为反应上下文 API 编写一个 HOC,它将在上下文 api 消费者中包装组件。

我的要求是:

  1. 需要维护对道具的完整类型检查
  2. 我需要能够在将上下文 api 提供的状态作为道具添加之前对其进行子集化(这也需要完整的类型检查)

我目前拥有的代码是这样的(使用实用程序类型库):

特设:

export const withMainContext = <
T extends object,
X extends object,
Y = Intersection<Required<IAppContext>, X>,
Z = Diff<T, Required<IAppContext>>
>(
    Component: React.ComponentType<T>,
    subsetStateCallback: (state: IAppContext) => Y = 
        (state) => state as unknown as Y
  ): React.SFC<Z> => (props: Z) => {
      return <AppContext.Consumer>
        {(state: IAppContext) => {
            const newState = subsetStateCallback(state)
            return <Component {...props} {...newState}/>
        }}
        </AppContext.Consumer>
  }

零件:

interface ItestOtherProps {
     one: string;
     two: number;
     three: string;
}
type ItestAppProps = Required<Pick<IAppContext, 'workflows'>>

type ITestProps = ItestOtherProps & ItestAppProps

class Test extends React.Component<ITestProps, {}> {
     public render(): JSX.Element {
         return null
     }
}

const Testy = withMainContext<ITestProps, ItestAppProps>(
     Test,
     (state: Required<IAppContext>): ItestAppProps => {return {workflows: state.workflows}}
)


const useTesty = () => {
     return <Testy one={""} two={0} three={""}/>
}

Diff 和 Intersection 从实用程序类型导入并在此处定义: https ://github.com/piotrwitek/utility-types

如果我可以稍微简化一下,或者不必将状态转换为未知,然后在回调的默认值中将其设置为 Y,那就太棒了。

有任何想法吗?

谢谢!

4

0 回答 0