const Button = styled.button`
background: blue;
color: white;
&:hover {
background: gray;
color: black;
}
`;
render(<Button> 點我!</Button>);
const Button = styled.button<{ primary?: boolean }>`
background: ${props => (props.primary ? 'pink' : 'blue')};
color: ${props => (props.primary ? 'white' : 'green')};
&:hover {
background: gray;
color: black;
}
`;
render(
<div>
<Button> 點我!</Button>
<Button primary> 點我!</Button>
</div>
);
const Button = styled.button`
background: blue;
color: white;
&:hover {
background: gray;
color: black;
}
`;
const CoolButton = styled(Button)`
background: yellow;
color: pink;
&:hover {
background: pink;
color: yellow;
}
`;
render(
<div>
<Button> 點我!</Button>
<CoolButton> 點我!</CoolButton>
</div>
);
如 MATERIAL-UI, Ant Design 等等,目前都有支援 styled-components 互動了
import Button from '@material-ui/core/Button';
const ChillButton = styled(Button)`
font-weight: 900;
text-transform: inherit;
`;
render(
<ChillButton variant="contained" color="primary">
Yoyoyo 點我!
</ChillButton>
);
import Button from '@material-ui/core/Button';
const ChillButton = styled(Button)`
color: blue !important;
font-weight: 900;
text-transform: inherit;
`;
render(
<ChillButton variant="contained" color="primary">
Yoyoyo 點我!
</ChillButton>
);
import { StylesProvider } from '@material-ui/core/styles';
render(
<StylesProvider injectFirst>
<App />
</StylesProvider>
);
透過綁定 className 使 styled-components 能注入樣式,此範例來自官網 styling-any-component
// from official document https://styled-components.com/docs/basics#styling-any-component
// This could be react-router-dom's Link for example
const Link = ({ className, children }) => (
<a className={className}>{children}</a>
);
const StyledLink = styled(Link)`
color: palevioletred;
font-weight: bold;
`;
render(
<div>
<Link>Unstyled, boring Link</Link>
<br />
<StyledLink>Styled, exciting Link</StyledLink>
</div>
);
const StyledTitle = styled.h2`
font-weight: 800;
font-size: 20px;
`;
const StyledSection = styled.div`
display: flex;
align-items: center;
& > ${StyledTitle} {
margin-right: 20px;
padding: 50px;
}
`;
render(
<StyledSection>
<StyledTitle>You're the best!</StyledTitle>
</StyledSection>
);
Icon 包在 Button 底下,有時我們會希望當 Button 被 hover 到時,Icon 的樣式也能一起動態改變樣式 React. 7 tricks to work with Styled Components Official Doc [Referring to other components]
const Button = styled.button<{ primary?: boolean }>`
background: ${props => (props.primary ? 'pink' : 'blue')};
color: ${props => (props.primary ? 'white' : 'green')};
&:hover {
background: gray;
color: black;
}
`;
const Icon = styled.i`
color: white;
background-color: orange;
font-size: 1.5 rem;
${Button}:hover & {
color: black;
}
`;
render(
<Button>
Click me<Icon>icon </Icon>
</Button>
);