【问题标题】:Emotion.js How to use dynamic style in object style?Emotion.js 如何在对象样式中使用动态样式?
【发布时间】:2020-02-09 12:52:44
【问题描述】:
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 })
)

【问题讨论】:

    标签: reactjs styled-components emotion


    【解决方案1】:

    除了@coreyward 的回答,您还可以使用更具可读性的方法,并执行以下操作 -

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

    同样,你可以破坏props -

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

    【讨论】:

      【解决方案2】:

      这是您从文档中复制的一个不好的示例,实际上导致 color 道具被写入 Container 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>
      )
      

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

      const Container = styled.div`
        color: ${props => props.color};
      `
      
      // or...
      
      const Container = ({ color, ...props }) => <div css={{ color }} {...props} />
      

      【讨论】:

      • const Container = styled.div` color: ${props => props.color}; `如果你的道具没有颜色会怎样?好像没有指定颜色样式?
      • @eugene Emotion 会自动丢弃虚假的非数字值(例如falsenullundefined)。
      猜你喜欢
      • 2020-02-10
      • 2021-01-24
      • 2017-05-30
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 2021-10-25
      • 2020-03-24
      • 2020-02-07
      相关资源
      最近更新 更多