【问题标题】:How to add conditional styles in emotion/react?如何在情感/反应中添加条件样式?
【发布时间】:2022-06-19 01:11:29
【问题描述】:

我正在使用反应和情绪。我需要根据布尔值更改元素的样式。下面的代码不起作用。如何正确组合多种样式?

import { css } from "@emotion/react"

const navSticky = css({
  transform: "translateY(-10px)",
})
const navStyle = css({
  background: "red",
})

... 

 <nav css={isSticky ? {...navStyle, ...navSticky} : navStyle}> </nav>

【问题讨论】:

  • 如果使用className,通常可以做这样的事情(使用反引号):className={`${styles.style1} ${styles.style2}`}。不知道same是否应该在这里工作?值得一试吗?

标签: reactjs emotion


【解决方案1】:

作为第一个变体,我建议为此使用样式组件。将背景设置为基本属性,如果 isSticky 属性已通过 true 值传递,则设置变换。

作为第二个变体,我建议更正您的示例。将 JSX Pragma 与来自 '@emotion/react' 的 jsx 函数一起使用。这允许使用 css 道具。文档:https://emotion.sh/docs/css-prop#jsx-pragma

// first variant

const Nav = styled.nav`
  background: red;
  transform: ${p => p.isSticky && "translateY(-10px)"};
`

const App = () => <Nav isSticky={true}>Some Elements</Nav>

// second variant

/** @jsx jsx */
import {jsx} from '@emotion/react'

const navSticky = {
  transform: 'translateY(-10px)',
}

const navStyle = {
  background: 'red',
}

const App = () => (
  <nav css={isSticky ? {...navStyle, ...navSticky} : navStyle}>Some Elements</nav>
)

【讨论】:

    猜你喜欢
    • 2021-04-23
    • 2022-11-21
    • 2020-02-26
    • 2021-11-13
    • 2018-09-24
    • 2022-11-05
    • 2019-10-31
    • 2021-06-17
    • 2021-11-01
    相关资源
    最近更新 更多