【问题标题】:I want to reuse certain CSS properties in Emotion/styled component我想在 Emotion/styled 组件中重用某些 CSS 属性
【发布时间】:2022-01-10 05:34:16
【问题描述】:
import styled from '@emotion/styled';

type ColorProps = {
    Coloured: boolean,
}

const BoxStyled = styled.div`
    ${(props:ColorProps) => 
    props.Coloured ? {
    
    background: "#304f8f",
    border: "1.85px solid #304f8f",
    color: "white",
    width: "4rem",
    height: "2.5rem",
    padding:"0 11px" 
} :
{
    
    border: "1.98px solid #2c8090",
    width: "4rem",
    height: "2.5rem",
    padding:"0 11px" 
}
}`

在 BoxStyled 中我不想写 width:"4rem", height:"2.5rem", padding:"0 11px" 两次我该如何实现?

【问题讨论】:

    标签: css reactjs properties styled-components emotion


    【解决方案1】:

    使用css 制作样式变量。

    import { css } from 'styled-components'
    
    const reuse = css`
      width: 4rem;
      height: 2.5rem;
      padding: 0 11px;
    `
    
    const StyleA = styled.div`
      background-color: black;
      ${reuse}
    `
    
    const StyleB = styled.div`
      background-color: red;
      ${reuse}
    `
    

    查看this了解更多信息。

    【讨论】:

    • 谢谢队友,我是新手,我已经尝试过你说的但这是一个简单的错误,只是写 width: 4rem;而不是宽度:“4rem”,
    • 没问题!希望你能做到:)
    【解决方案2】:

    您可以定义主样式并在需要时更改覆盖新样式。

    import styled from '@emotion/styled';
    
    type ColorProps = {
        Coloured: boolean,
    }
    
    const BoxStyled = styled.div`
    
        border: "1.98px solid #2c8090",
        width: "4rem",
        height: "2.5rem", 
        padding:"0 11px" 
    
        ${(props:ColorProps) => 
        props.Coloured && {
          background: "#304f8f",
          border: "1.85px solid #304f8f",
          color: "white",
       }
    }`
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2021-02-19
    • 2020-05-11
    • 2023-03-24
    • 2018-07-03
    • 2021-05-29
    • 1970-01-01
    • 2019-07-28
    • 2021-07-09
    • 2022-08-19
    相关资源
    最近更新 更多