【问题标题】:What is the best way to style nested elements in React?在 React 中设置嵌套元素样式的最佳方式是什么?
【发布时间】:2019-10-08 23:55:15
【问题描述】:

我正在尝试使用 CSS 设置几个 div 元素的样式。在普通 CSS 中,可以使用以下代码:

.wrapper{
  width: 300px;
  height: 500px;
  .container {
    width: 50%;
    height: 20%;
    .inside {
      color: red;
    }
  }
}

然而,为了在 CSS 模块中使用相同的 CSS,它需要编写如下:

.wrapper{
      width: 300px;
      height: 500px;
}

.wrapper .container {
        width: 50%;
        height: 20%;
}

.wrapper .container .inside {
          color: red;
        }

有没有更好更简单的方法来做到这一点?因为当有很多元素时,这种方法似乎更复杂!

【问题讨论】:

标签: html css reactjs


【解决方案1】:

您可以使用 styled-components 库。

一个例子是

const Wrapper = styled.div`
    width: 300px;
    height: 500px;

    &.container{
        width: 50%;
        height: 20%;

        &.inside{
            color:red;
        }
    }

`

但是我建议以更反应的方式来做这件事


const Wrapper = styled.div`
    width: 300px;
    height: 500px;
`
const Container = styled.div`
    width: 50%;
    height: 20%;
`
const Inside = styled.div`
    color: red;
`

【讨论】:

    猜你喜欢
    • 2022-12-12
    • 1970-01-01
    • 2010-10-14
    • 2012-06-04
    • 2019-12-11
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    相关资源
    最近更新 更多