|
|
@ -1,18 +1,26 @@ |
|
|
|
// Create a theme context, defaulting to light theme
|
|
|
|
// highlight-next-line
|
|
|
|
// highlight-range{1-4}
|
|
|
|
// Context lets us pass a value deep into the component tree
|
|
|
|
// without explicitly threading it through every component.
|
|
|
|
// Create a context for the current theme (with "light" as the default).
|
|
|
|
const ThemeContext = React.createContext('light'); |
|
|
|
|
|
|
|
function ThemedButton(props) { |
|
|
|
// highlight-range{1,3-5}
|
|
|
|
// The ThemedButton receives the theme from context
|
|
|
|
return ( |
|
|
|
<ThemeContext.Consumer> |
|
|
|
{theme => <Button {...props} theme={theme} />} |
|
|
|
</ThemeContext.Consumer> |
|
|
|
); |
|
|
|
class App extends React.Component { |
|
|
|
render() { |
|
|
|
// highlight-range{1-3,5}
|
|
|
|
// Use a Provider to pass the current theme to the tree below.
|
|
|
|
// Any component can read it, no matter how deep it is.
|
|
|
|
// In this example, we're passing "dark" as the current value.
|
|
|
|
return ( |
|
|
|
<ThemeContext.Provider value="dark"> |
|
|
|
<Toolbar /> |
|
|
|
</ThemeContext.Provider> |
|
|
|
); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
// An intermediate component
|
|
|
|
// highlight-range{1,2}
|
|
|
|
// A component in the middle doesn't have to
|
|
|
|
// pass the theme down explicitly anymore.
|
|
|
|
function Toolbar(props) { |
|
|
|
return ( |
|
|
|
<div> |
|
|
@ -21,13 +29,14 @@ function Toolbar(props) { |
|
|
|
); |
|
|
|
} |
|
|
|
|
|
|
|
class App extends React.Component { |
|
|
|
render() { |
|
|
|
// highlight-range{2,4}
|
|
|
|
return ( |
|
|
|
<ThemeContext.Provider value="dark"> |
|
|
|
<Toolbar /> |
|
|
|
</ThemeContext.Provider> |
|
|
|
); |
|
|
|
} |
|
|
|
function ThemedButton(props) { |
|
|
|
// highlight-range{1-3,6}
|
|
|
|
// Use a Consumer to read the current theme context.
|
|
|
|
// React will find the closest theme Provider above and use its value.
|
|
|
|
// In this example, the current theme is "dark".
|
|
|
|
return ( |
|
|
|
<ThemeContext.Consumer> |
|
|
|
{theme => <Button {...props} theme={theme} />} |
|
|
|
</ThemeContext.Consumer> |
|
|
|
); |
|
|
|
} |
|
|
|