Brian Vaughn
7 years ago
4 changed files with 83 additions and 1 deletions
@ -0,0 +1,34 @@ |
|||
// highlight-next-line
|
|||
const ThemeContext = React.createContext('light'); |
|||
|
|||
class ThemeProvider extends React.Component { |
|||
state = {theme: 'light'}; |
|||
|
|||
render() { |
|||
// highlight-range{2}
|
|||
return ( |
|||
<ThemeContext.Provider value={this.state.theme}> |
|||
{this.props.children} |
|||
</ThemeContext.Provider> |
|||
); |
|||
} |
|||
} |
|||
|
|||
class ThemedButton extends React.Component { |
|||
render() { |
|||
// highlight-range{2-4}
|
|||
return ( |
|||
<ThemeContext.Consumer> |
|||
{theme => { |
|||
const background = theme ? '#fff' : '#000'; |
|||
|
|||
return ( |
|||
<button style={{background}}> |
|||
{this.props.children} |
|||
</button> |
|||
); |
|||
}} |
|||
</ThemeContext.Consumer> |
|||
); |
|||
} |
|||
} |
@ -0,0 +1,42 @@ |
|||
import PropTypes from 'prop-types'; |
|||
import React from 'react'; |
|||
|
|||
class ThemeProvider extends React.Component { |
|||
// highlight-range{1-3}
|
|||
static childContextTypes = { |
|||
theme: PropTypes.string, |
|||
}; |
|||
|
|||
state = { |
|||
theme: 'light', |
|||
}; |
|||
|
|||
// highlight-range{1-5}
|
|||
getChildContext() { |
|||
return { |
|||
theme: state.theme, |
|||
}; |
|||
} |
|||
|
|||
render() { |
|||
return this.props.children; |
|||
} |
|||
} |
|||
|
|||
class ThemedButton extends React.Component { |
|||
// highlight-range{1-3}
|
|||
static contextTypes = { |
|||
theme: PropTypes.string, |
|||
}; |
|||
|
|||
render() { |
|||
// highlight-next-line
|
|||
const background = this.context.theme ? '#fff' : '#000'; |
|||
|
|||
return ( |
|||
<button style={{background}}> |
|||
{this.props.children} |
|||
</button> |
|||
); |
|||
} |
|||
} |
Loading…
Reference in new issue