【问题标题】:Div with two syled components具有两个样式组件的 Div
【发布时间】:2021-02-07 04:53:03
【问题描述】:

我对样式化组件还很陌生,我正在尝试将带有原始 CSS 的网站转换为样式化组件。我的问题是我有一个包含多个类的 div,但我不知道如何使用样式化组件呈现我的 Gatsby 前端

例如下面的sn-p:

<div className="section-center hero-center">
        
</div>

我首先创建了两个样式化的组件文件,如下所示:

import styled from "styled-components"
export const SectionCenter = styled.div`
      width: 90vw;
      margin: 0 auto;
      max-width: 1170px;
    `

和第二个组件:

import styled from "styled-components"
export const HeroCenter = styled.div`
  height: 100%;
  display: grid;
  align-items: center;
`

在我的 Hero.js 组件中,我执行导入语句

import React from "react"
import * as styled from '../styled'

const Hero = () => {
  return (
    <styled. SectionCenter>
  <styled.HeroCenter>

// content goes here

</styled.HeroCenter>
            </styled.SectionCenter >
            )
}

export default Hero

这是我目前所拥有的,但它不是原始 div 的方式,一个 div 有两种样式。还有另一种方法可以实现吗?一个 div 上有两种样式,类似于 vanilla css?

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    样式可以扩展。因此,如果 heroCenter 是 SectionCenter 的自定义版本,您可以执行以下操作:

    import styled from "styled-components"
    export const SectionCenter = styled.div`
          width: 90vw;
          margin: 0 auto;
          max-width: 1170px;
    `
    export const HeroCenter = styled(SectionCenter)`
      width: 100vw;
    `
    

    那么 Hero.js 可以只使用 HeroCenter 组件。更多详情请见official docs

    【讨论】:

    • 对不起,我必须编辑我的请求,因为我忘了粘贴正确的代码,但我的请求仍然是一样的,如果你在 vanilla css 中的同一个 div 上有两种样式然后转换它到样式化的组件
    猜你喜欢
    • 2020-08-14
    • 2022-07-05
    • 2021-02-10
    • 2021-02-26
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多