【问题标题】:How to Use Classes in Styled-Component如何在样式化组件中使用类
【发布时间】:2019-07-29 13:10:57
【问题描述】:

我是样式组件的新手。我想将自定义 CSS 转换为 Styled-Component。我已经在React 文件中使用了className

App.js

<div className="left-menus">
      {menus.map(item => {
          return (
            <Link to={item.name} name={item.name} key={item.name}
              className={this.state.activeMenu === item.name ? 'menu active' : 'menu' }
              onClick={() => this.setState({ activeMenu: item.name })}
              >
              <Icon name={item.icon} size="large"/>
              <span>{item.name}</span>
            </Link>
          )
      })}
    </div>

App.css

.left-menus {
  position: fixed;
  width: 200px;
  padding-right: 0 !important;
  background-color: #fff;
  height: 100%;
  margin-top: 20px;
  top: 47px;
  font-size: 12px !important;
  border-right: 2px solid #e8e8ec; }
  .left-menus .menu {
    color: #4a4a4a;
    width: 100%;
    display: block;
    cursor: pointer;
    text-transform: capitalize !important;
    padding: 15px 10px 15px 18px; }
    .left-menus .menu .angle.down.icon,
    .left-menus .menu .angle.up.icon {
      right: 10px;
      position: absolute; }
  .left-menus .menu .icon:first-child {
    margin-right: 10px; }
  .left-menus .menu.active {
    border-right: 4px solid #3cbfc8;
    background-color: #f8f8f8; }
  .left-menus .sub-menu-container .sub-menu {
    display: none;
    height: 0;
    transition: 0.3s all ease; }
  .left-menus .sub-menu-container.active .sub-menu {
    display: block;
    height: 100%;
    text-transform: capitalize;
    transition: 0.3s all ease; }
    .left-menus .sub-menu-container.active .sub-menu a {
      color: #4a4a4a; }
    .left-menus .sub-menu-container.active .sub-menu .icon {
      margin: 10px 10px 0 10px; }

【问题讨论】:

  • stackoverflow.com/q/38545219/1531971 相关,如果不是重复的话。还有其他的。所以你应该展示你的研究。
  • 仅从样式和维护的角度来看,您可能需要考虑摆脱像这样的深度嵌套的 CSS 树。您不一定需要带有样式组件的类名结构

标签: reactjs ecmascript-6 styled-components


【解决方案1】:

带有类选择器的 CSS 只会匹配属于类的元素。

要为一个样式化的组件提供该类,您需要在实例化它时进行。

例如:

const MyStyledComponent = styled.div`

背景:红色; `;

const myFunctionComponent = () => {
    const myClass = "left-menus";

    return(
        <div>
            Here is MyStyledComponent
            <MyStyledComponent className={myClass}>
                Example
            </MyStyledComponent>
        </div>
    );
}

如果您有想要应用的现有样式表,则样式化组件很可能不是适合该工作的工具。

【讨论】:

    猜你喜欢
    • 2019-01-14
    • 2021-11-01
    • 2019-10-07
    • 2021-07-04
    • 2021-09-29
    • 2020-09-26
    • 2020-09-22
    • 2014-01-22
    • 2021-03-24
    相关资源
    最近更新 更多