@emotion/styled中文文档总结

原文链接:https://emotion.sh/docs/styled

styled是一种创建带有样式的React组件的方法

1.写一个带样式的组件

语法:styled.元素名`样式`

import styled from '@emotion/styled'
const Button = styled.button`
  color: turquoise;
`
render()

2.通过参数控制样式

import styled from '@emotion/styled'
import {Fragment} from 'react';
const Button = styled.button`
  color: ${props =>
    props.primary ? 'hotpink' : 'turquoise'};
`

  
  

3.通过传className创建组件

语法:styled( ({className}) => (

text p>) )`样式`
分析:相当于把样式通过className传递给了元素

import styled from '@emotion/styled'
const Basic = ({ className }) => (
  
Some text
) const Fancy = styled(Basic)` color: hotpink; ` render()

4.创建与某个组件相同的样式

语法:样式组件.withComponent('元素')

import styled from '@emotion/styled'
const Section = styled.section`
  background: #333;
  color: #fff;
`
// Aside样式跟Section样式相同
const Aside = Section.withComponent('aside')
render(
  
This is a section
)

5.嵌套写法 - ${子组件}

语法:父组件 = styled.元素`${子组件} {样式}`

import styled from '@emotion/styled'
const Child = styled.div`
  color: red;
`
const Parent = styled.div`
  ${Child} {
    color: green;
  }
`
render(
  
Green because I am inside a Parent Red because I am not inside a Parent
)

6.嵌套写法 - 对象(键值对)

语法:父组件 = styled.元素(
{
[子组件]: {样式}}
)

import styled from '@emotion/styled'
const Child = styled.div({
  color: 'red'
})
const Parent = styled.div({
  [Child]: {
    color: 'green'
  }
})
render(
  
green red
)

7.对象样式

import styled from '@emotion/styled'
const H1 = styled.h1(
  {
    fontSize: 20
  },
  props => ({ color: props.color,  width:props.width })
)
render(

This is lightgreen.

)

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(

This is lightgreen.

)

9.动态样式

import styled from '@emotion/styled'
import { css } from '@emotion/core'
const dynamicStyle = props =>
  css`
    color: ${props.color};
  `
const Container = styled.div`
  ${dynamicStyle};
`
render(
  
    This is lightgreen.
  
)

10.as prop

要使用样式化组件中的样式但要更改呈现的元素,可以使用as prop。

import styled from '@emotion/styled'

const Button = styled.button`
  color: hotpink;
`
render(
  
)

11.嵌套元素样式写法

import styled from '@emotion/styled'
const Example = styled('span')`
  color: lightgreen;
  & > a {
    color: hotpink;
  }
`
render(
  
    This is nested.
  
)

你可能感兴趣的:(@emotion/styled中文文档总结)