在 React 專案使用 Styled Components 樣式化元件

使用

建立一個帶有樣式的元件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const Button = styled.a`
/* This renders the buttons above... Edit me! */
display: inline-block;
border-radius: 3px;
padding: 0.5rem 0;
margin: 0.5rem 1rem;
width: 11rem;
background: transparent;
color: white;
border: 2px solid white;

/* The GitHub button is a primary button
* edit this to target it specifically! */
${props => props.primary && css`
background: white;
color: black;
`}
`

render(
<div>
<Button
href="https://github.com/styled-components/styled-components"
target="_blank"
rel="noopener"
primary
>
GitHub
</Button>

<Button as={Link} href="/docs">
Documentation
</Button>
</div>
)

建立一個複寫樣式的元件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const Button = styled.button`
color: palevioletred;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;

const TomatoButton = styled(Button)`
color: tomato;
border-color: tomato;
`;

render(
<div>
<Button>Normal Button</Button>
<TomatoButton>Tomato Button</TomatoButton>
</div>
);

樣式化一個既有的元件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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>
);

參考資料