styled是一種創(chuàng)建帶有樣式的React組件的方法
1.寫一個(gè)帶樣式的組件
語法:styled.元素名`樣式`
import styled from '@emotion/styled'
const Button = styled.button`
color: turquoise;
`
render(<Button>This my button component.</Button>)
2.通過參數(shù)控制樣式
import styled from '@emotion/styled'
import {Fragment} from 'react';
const Button = styled.button`
color: ${props =>
props.primary ? 'hotpink' : 'turquoise'};
`
<Fragment>
<Button primary>This is a primary button.</Button>
<Button>This is a primary button.</Button>
</Fragment>
3.通過傳className創(chuàng)建組件
語法:styled( ({className}) => (<p className={className}>text</
p>) )`樣式`
分析:相當(dāng)于把樣式通過className傳遞給了元素
import styled from '@emotion/styled'
const Basic = ({ className }) => (
<div className={className}>Some text</div>
)
const Fancy = styled(Basic)`
color: hotpink;
`
render(<Fancy />)
4.創(chuàng)建與某個(gè)組件相同的樣式
語法:樣式組件.withComponent('元素')
import styled from '@emotion/styled'
const Section = styled.section`
background: #333;
color: #fff;
`
// Aside樣式跟Section樣式相同
const Aside = Section.withComponent('aside')
render(
<div>
<Section>This is a section</Section>
<Aside>This is an aside</Aside>
</div>
)
5.嵌套寫法 - ${子組件}
語法:父組件 = styled.元素`${子組件} {樣式}`
import styled from '@emotion/styled'
const Child = styled.div`
color: red;
`
const Parent = styled.div`
${Child} {
color: green;
}
`
render(
<div>
<Parent>
<Child>Green because I am inside a Parent</Child>
</Parent>
<Child>Red because I am not inside a Parent</Child>
</div>
)
6.嵌套寫法 - 對(duì)象(鍵值對(duì))
語法:父組件 = styled.元素(
{
[子組件]: {樣式}}
)
import styled from '@emotion/styled'
const Child = styled.div({
color: 'red'
})
const Parent = styled.div({
[Child]: {
color: 'green'
}
})
render(
<div>
<Parent>
<Child>green</Child>
</Parent>
<Child>red</Child>
</div>
)
7.對(duì)象樣式
import styled from '@emotion/styled'
const H1 = styled.h1(
{
fontSize: 20
},
props => ({ color: props.color, width:props.width })
)
render(<H1 color="lightgreen" width="200px">This is lightgreen.</H1>)
8.
import isPropValid from '@emotion/is-prop-valid'
import styled from '@emotion/styled'
const H1 = styled('h1', {
shouldForwardProp: prop =>
isPropValid(prop) && prop !== 'color'
})(props => ({
color: 'hotpink'
}))
render(<H1 color="lightgreen">This is lightgreen.</H1>)
9.動(dòng)態(tài)樣式
import styled from '@emotion/styled'
import { css } from '@emotion/core'
const dynamicStyle = props =>
css`
color: ${props.color};
`
const Container = styled.div`
${dynamicStyle};
`
render(
<Container color="lightgreen">
This is lightgreen.
</Container>
)
10.as prop
要使用樣式化組件中的樣式但要更改呈現(xiàn)的元素赂摆,可以使用as prop执解。
import styled from '@emotion/styled'
const Button = styled.button`
color: hotpink;
`
render(
<Button
as="a"
>
Emotion on GitHub
</Button>
)
11.嵌套元素樣式寫法
import styled from '@emotion/styled'
const Example = styled('span')`
color: lightgreen;
& > a {
color: hotpink;
}
`
render(
<Example>
This is <a>nested</a>.
</Example>
)