html - 在 React 中设置嵌套元素样式的最佳方式是什么?

标签 html css reactjs

我正在尝试使用 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;
        }

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

最佳答案

您可以使用 styled-components 库。

一个例子是

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

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

        &.inside{
            color:red;
        }
    }

`

但是我会建议以更 react 的方式来做


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

关于html - 在 React 中设置嵌套元素样式的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58295353/

相关文章:

html - CSS float :left causes thumbnails to align diagonal to each other. ..>.<

javascript - setTimeout ReactJS 与箭头函数 es6

jquery - 是否可以仅通过我的传统堆栈在客户端使用 React.js

css - 删除shinydashboardPlus中的左侧边栏(仅保留右侧)

javascript - 尝试设置状态,但函数返回 null

javascript - jquery .unload() 仅在 iframe 中访问的第一个页面触发

javascript - 响应 "Full Div"YouTube 视频

c# - 检测移动浏览器对 HTML5 支持的代码

html - 在 chrome 66 中禁用自动完成

html - 非按比例缩放 SVG 图像以适合剩余空间