// Style guide definition
const styleGuide = {
cloudy: '#F2F4F7',
darkGray: '#4A637C',
gray: '#7A8D9F',
// ...more colors or mixins
};
return (
// The theme styles are available everywhere (thanks to React's context API)
// Now you can access to "props.theme.gray" on any component
<ThemeProvider theme={styleGuide}>
<App>
<Switch>
<AuthRoute auth={auth} exact path="/" component={DashboardView} />
<AuthRoute auth={auth} path="/profile" component={DashboardView} />
<Route path="/login" component={LoginView} />
<Route path="/logout" component={LogoutView} />
{/* ...more routes */}
<Route component={NotFoundView} />
</Switch>
</App>
</ThemeProvider>
);
可以这样去定义一个 button:
// Define our button, but with the use of props.theme this time
const Button = styled.button`
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border-radius: 3px;
/* Color the border and text with theme properties */
color: ${props => props.theme.darkGray};
border: 2px solid ${props => props.theme.darkGray};
`;
Embracing the power of styled-components
总结 Styled Component 的三个优点:
无需 import 引入即可使用全局主题变量
可以这样去定义一个 button:
方便重构
由于无需引入 CSS 文件, 在重构的时候无需考虑文件路径改变