首页 > 解决方案 > ReactJs StyledComponent 和 ClassName

问题描述

你好我有一个问题我相信我的代码对于简单的事情来说太大了

基本上我有一个网站的包装:

export const Wrapper = styled.div`
    min-height:100vh !important;
`;

我的标题现在是这样的:

    <Styled.WrapHeader>
        <DefaultContainer>
            <Styled.NavStickey />
        </DefaultContainer>
    </Styled.WrapHeader>

我使用了 3 个 div 来制作一个简单的 100% 宽度的 div 和一个导航栏为 css 的容器:

const WrapHeader = styled.div`
    background: #1269DB;
    height: 130px;
    width:100%;
`;

const NavStickey = styled.div`
    width:100%;
    height: 60px;
    background: red;   
`;

在这里我有我的容器:

export const DefaultContainer = styled.div`
    display: flex;
    flex-direction: row;
    -webkit-box-align: center;
    align-items: center;
    -webkit-box-pack: justify;
    justify-content: space-between;
    background: transparent !important;
`

我认为非常大我想为一个类分离容器的边距和填充,并在 div 中调用 className 我将如何在样式中得到它?

像这样:

.divct{
        display: flex;
        flex-direction: row;
        -webkit-box-align: center;
        align-items: center;
        -webkit-box-pack: justify;
        justify-content: space-between;
        background: transparent !important;
}
.container {
        max-width: 1000px;
        padding: 0px 30px;
        margin: 0px auto;
}

div className = "divct container"

标签: reactjsstyled-components

解决方案


您可以像这样创建 CSS 模板的片段:

import styled, { css } from 'styled-components'

// Not a styled component, just a css template.
const DivContainer = css`
  display: flex;
  flex-direction: row;
  -webkit-box-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  justify-content: space-between;
  background: transparent !important;
`

const Container = css`
  max-width: 1000px;
  padding: 0px 30px;
  margin: 0px auto;
`

然后,您可以将它们组合成一个样式化的组件,就像在常规组件中加入两个类名一样:

const WrapHeader = styled.div`
  background: #1269DB;
  height: 130px;
  width:100%;
  ${DivContainer}
  ${Container}
`

这就像任何其他模板字符串一样工作(因为它们就是这样)。所以结果将合并所有样式,如下所示:

// This is what the result will look like internally.
const WrapHeader = styled.div`
  background: #1269DB;
  height: 130px;
  width:100%;
  display: flex;
  flex-direction: row;
  -webkit-box-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  justify-content: space-between;
  background: transparent !important;
  max-width: 1000px;
  padding: 0px 30px;
  margin: 0px auto;
`

推荐阅读