所以我当前正在为react context API编写一个HOC,它将组件包装在context api使用者中。
我的要求是:
我当前拥有的代码是这个(使用实用程序类型库):
HOC:
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之前不必将状态强制转换为未知状态,那将是很棒的事情。
有什么想法吗?
谢谢!