Created
August 1, 2018 05:52
-
-
Save ThaddeusJiang/6d2e3f742aa79f1cc614be6d4015ea9b to your computer and use it in GitHub Desktop.
React Context API Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 创建一个 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