Last active
July 12, 2019 08:31
-
-
Save radzserg/dd8161e81bb5227f3511a48be948009a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as React from "react"; | |
| import DIContext from "./DIContext"; | |
| import { IDIContainer } from "rsdi"; | |
| interface DIResolutionConfig { | |
| [propName: string]: string; | |
| } | |
| type Without<T, K> = { | |
| [L in Exclude<keyof T, K>]: T[L] | |
| }; | |
| export default function withInjection<T, K>( | |
| WrappedComponent: React.ComponentType<T>, | |
| diConfig: DIResolutionConfig | |
| ): React.ComponentType<Without<T, keyof K>> { | |
| const name = WrappedComponent.displayName || WrappedComponent.name; | |
| class InjectionWrapper extends React.Component<any, any> { | |
| static contextType = DIContext; | |
| static displayName = `withInjection(${name})`; | |
| static WrappedComponent = WrappedComponent; | |
| render() { | |
| const diContainer = this.context as IDIContainer; | |
| const diProps: any = {}; | |
| Object.keys(diConfig).forEach((propName: string) => { | |
| const definitionName = diConfig[propName]; | |
| diProps[propName] = diContainer.get(definitionName); | |
| }); | |
| const { ...restProps } = this.props; | |
| return <WrappedComponent {...diProps} {...(restProps as T)} />; | |
| } | |
| } | |
| return InjectionWrapper; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment