【问题标题】:styled-components with custom component not applying styles具有自定义组件的样式组件不应用样式
【发布时间】:2021-02-08 14:24:19
【问题描述】:

我尝试了以下代码来设置 react-id-swiper 实现的内部元素的样式: https://kidjp85.github.io/react-id-swiper/

import Swiper from 'react-id-swiper';
import styled from 'styled-components';

    const MySwiper = ({ className, children }) => (
        <Swiper className={className} {...params}>
            {children}
        </Swiper>
    )
    
    const StyledMySwiper = styled(MySwiper)`
        .swiper-container{
            background-color: red !important;
        }
        .swiper-slide{
            background-color: red !important;
        }
        .swiper-wrapper{
            background-color: red !important;
        }
    `;

然后在我的组件中使用它:

function CustomSwiper(props) {
    return (
            <StyledMySwiper>
                <div>Slide #1</div>
                <div>Slide #2</div>
                <div>Slide #3</div>
                <div>Slide #4</div>
                <div>Slide #5</div>
            </StyledMySwiper>
    );
}

export default CustomSwiper;

但未应用样式。 我在这里做错了什么?

【问题讨论】:

    标签: javascript reactjs material-ui styled-components


    【解决方案1】:

    StyledTestComponent 中删除.h1,自定义样式将应用于TestComponent

    const StyledTestComponent = styled(MyTestComponent)`
       {
        color: red;
        font-size: 100px;
      }
    `;
    

    如果TestComponent 有下面这样的孩子,

    function TestComponent({ className }) {
        return (
            <h1 className={className}>
              <div className='child'> test div element</div> //child
                aaaaasdfsdfsd
            </h1>
        );
    }
    

    您可以使用div 标签或className 来应用样式,

     const StyledTestComponent = styled(MyTestComponent)`
        {
        color: red;
        font-size: 100px;
      } // This will apply to the main container
    
      .child {
        color: green;
        font-size: 100px;
      } // This will apply to child element
    `;
    

    【讨论】:

    • 谢谢,但是如何通过类名覆盖内部类样式?
    • 子元素可以使用classNametagname。更新了答案
    • 仍然无法正常工作,我已经编辑了示例以显示在组件上我尝试更改内部元素的样式
    猜你喜欢
    • 2020-04-28
    • 2018-03-22
    • 2019-03-03
    • 2019-10-18
    • 2020-12-09
    • 2022-06-23
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多