Skip to content

Instantly share code, notes, and snippets.

@ThaddeusJiang
Created August 1, 2018 05:52
Show Gist options
  • Save ThaddeusJiang/6d2e3f742aa79f1cc614be6d4015ea9b to your computer and use it in GitHub Desktop.
Save ThaddeusJiang/6d2e3f742aa79f1cc614be6d4015ea9b to your computer and use it in GitHub Desktop.
React Context API Example
// 创建一个 theme Context, 默认 theme 的值为 light
const ThemeContext = React.createContext('light');
function ThemedButton(props) {
// ThemedButton 组件从 context 接收 theme
return (
<ThemeContext.Consumer>
{theme => <Button {...props} theme={theme} />}
</ThemeContext.Consumer>
);
}
// 中间组件
function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
);
}
class App extends React.Component {
render() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment