【问题标题】:Styled Component Custom CSS in ReactJSReactJS 中的样式化组件自定义 CSS
【发布时间】:2021-04-03 12:29:32
【问题描述】:

我实际上在使用 React 中的样式化组件处理 CSS 时遇到了麻烦。下面给出的是代码sn-p

import React from 'react';
import { Navbar, Container, Row, Col } from 'reactstrap';
import styled from 'styled-components';

const Styles = styled.div`
  .navbar {
    background-color: black;
    position: absolute;
    bottom: 0;
    width: 100%;
  }
  .h1 {
    color: white;
  }
`;

const Footer = () => {
  return (
    <Styles>
      <Navbar>
        <Container>
          <Row>
            <Col sm={{ size: 4 }}>
              <h1>Hi</h1>
            </Col>
          </Row>
        </Container>
      </Navbar>
    </Styles>
  );
};

export default Footer;

我想要做的是将h1 标记的颜色更改为白色,但上面的自定义 CSS 不起作用。我也试过background-color,但问题仍然存在。

【问题讨论】:

    标签: javascript css reactjs jsx styled-components


    【解决方案1】:

    对于styled-components,您不应该使用类来设置元素样式。您应该为组件使用单独的包装器,这是重点。我想你想做这样的事情:

    import React from 'react';
    import { Navbar, Container, Row, Col } from 'reactstrap';
    import styled from 'styled-components';
    
    const StyledNavbar = styled(Navbar)`
      background-color: black;
      position: absolute;
      bottom: 0;
      width: 100%;
    `;
    
    const Header = styled.h1`
      color: white;
    `;
    
    const Footer = () => {
      return (
        <StyledNavbar>
          <Container>
            <Row>
              <Col sm={{ size: 4 }}>
                <Header>Hi</Header>
              </Col>
            </Row>
          </Container>
        </StyledNavbar>
      );
    };
    
    export default Footer;
    

    【讨论】:

    • 那么如果不定义另一个变量是不可能的,即Header
    • @Nimrod 但为什么呢?是styled-components的重点。
    【解决方案2】:

    您在 css 中使用了 .h1 类,而不是 h1 标记。

    https://styled-components.com/docs/basics#pseudoelements-pseudoselectors-and-nesting

    【讨论】:

    • 您能否提供有关解决方案的更多详细信息,我是 CSS 新手
    • .h1 作为一个类将类似于&lt;h1 class"h1"&gt;hi&lt;/h1&gt;。类是标签上的选择器/属性。这个标签是一个 h1
    • 使用styled.h1需要我再定义一个变量,难道不能在styled.div中定义吗?我只需要改变颜色。
    • 好的,我加了classname='h1',但还是不行。
    • 真的很抱歉,我认为您不需要另一个变量,我会删除它。看我上面的评论
    猜你喜欢
    • 2022-06-23
    • 2018-11-20
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 2018-03-22
    • 2023-04-04
    相关资源
    最近更新 更多