自定义组件未应用样式的样式组件

时间:2020-10-26 10:24:00

标签: javascript reactjs material-ui styled-components

我尝试了以下代码来设置由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;

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

1 个答案:

答案 0 :(得分:1)

.h1中删除StyledTestComponent,自定义样式将应用于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
`;
相关问题