-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
withTheme.js
51 lines (39 loc) 路 1.17 KB
/
withTheme.js
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
47
48
49
50
51
// @flow
/* globals ReactClass */
import React from 'react'
import PropTypes from 'prop-types'
import hoistStatics from 'hoist-non-react-statics'
import { CHANNEL } from '../models/ThemeProvider'
const wrapWithTheme = (Component: ReactClass<any>) => {
const componentName = (
Component.displayName ||
Component.name ||
'Component'
)
class WithTheme extends React.Component {
static displayName = `WithTheme(${componentName})`
static contextTypes = {
[CHANNEL]: PropTypes.func,
};
state: { theme?: ?Object } = {};
unsubscribe: () => void;
componentWillMount() {
if (!this.context[CHANNEL]) {
throw new Error('[withTheme] Please use ThemeProvider to be able to use withTheme')
}
const subscribe = this.context[CHANNEL]
this.unsubscribe = subscribe(theme => {
this.setState({ theme })
})
}
componentWillUnmount() {
if (typeof this.unsubscribe === 'function') this.unsubscribe()
}
render() {
const { theme } = this.state
return <Component theme={theme} {...this.props} />
}
}
return hoistStatics(WithTheme, Component)
}
export default wrapWithTheme