首页 > 解决方案 > Emotion.js 如何在对象样式中使用动态样式?

问题描述

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>
)

如何Container使用以下对象样式制作?

const H1 = styled.h1(
  {
    fontSize: 20
  },
  props => ({ color: props.color })
)

标签: reactjsstyled-componentsemotion

解决方案


这是你从文档中复制的一个不好的例子,它实际上导致color道具被写入容器 div,但本质上你会做这样的事情:

import styled from '@emotion/styled'
import { css } from '@emotion/core'

const dynamicStyle = props => ({ color: props.color })

const Container = styled.div`
  ${dynamicStyle};
`
render(
  <Container color="lightgreen">
    This is lightgreen.
  </Container>
)

为了理智和避免道具被传递给你的 React 元素,我推荐一种更像这样的方法:

const Container = styled.div`
  color: ${props => props.color};
`

// or...

const Container = ({ color, ...props }) => <div css={{ color }} {...props} />

推荐阅读