-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
46 lines (39 loc) · 1.21 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import * as React from "react";
import getDisplayName from "react-display-name";
interface ContextInterface {
[key: string]: any;
}
type createContextFactoryInterface = (
name: string,
contextParam: any,
onContextUpdateParam?: () => any
) => {
Provider: React.ComponentType<React.ProviderProps<ContextInterface>>;
connect: (
Component: React.SFC<any> | typeof React.Component
) => React.StatelessComponent<any>;
};
const createContextFactory: createContextFactoryInterface = (
name,
contextParam,
onContextUpdateParam
) => {
const { Consumer, Provider } = React.createContext({
[`${name}Context`]: contextParam,
[`on${name}ContextUpdate`]: onContextUpdateParam
});
const connect = (Component: React.SFC<any> | typeof React.Component) => {
const WithContext: React.SFC<{}> = (props: any) => (
<Consumer>
{(contextPayload: ContextInterface) => {
const context = { [`${name}Context`]: { ...contextPayload } };
return <Component {...props} {...context} />;
}}
</Consumer>
);
WithContext.displayName = `connect(${getDisplayName(Component)})`;
return WithContext;
};
return { Provider, connect };
};
export default createContextFactory;