【问题标题】:Reusability with Styled-Components in ReactReact 中样式化组件的可重用性
【发布时间】:2021-10-02 06:45:31
【问题描述】:

我需要在其他组件中使用我的自定义微调器。所以我做了一个可重复使用的微调器? 如何复制其样式并自定义其他样式?我只想更改stroke 或加载的颜色。请在这里检查我的代码

Spinner.js

import styled from 'styled-components'

const StyledSpinner = styled.svg`
  animation: rotate 1s linear infinite;
  width: 50px;
  height: 30px;

  & .path {
    stroke: #000000;
    stroke-linecap: round;
    animation: dash 1.5s ease-in-out infinite;
  }

  @keyframes rotate {
    100% {
      transform: rotate(360deg);
    }
  }
  @keyframes dash {
    0% {
      stroke-dasharray: 1, 150;
      stroke-dashoffset: 0;
    }
    50% {
      stroke-dasharray: 90, 150;
      stroke-dashoffset: -35;
    }
    100% {
      stroke-dasharray: 90, 150;
      stroke-dashoffset: -124;
    }
  }
`

const Spinner = () => (
  <StyledSpinner viewBox="0 0 50 50">
    <circle className="path" cx="25" cy="25" r="20" fill="none" strokeWidth="4" />
  </StyledSpinner>
)

export default Spinner

NewComponent.js

import CustomSpinner from '../Spinner'

const Spinner = styled(CustomSpinner)`
   & .path {
     stroke: #fff;
  }
`

【问题讨论】:

    标签: reactjs react-hooks styled-components


    【解决方案1】:

    您可以在 Spiner.js 组件中添加自定义样式,然后将其导出。在 NewComponent.js 中,您可以导出自定义 spiner 样式并以与 Spiner.js 中相同的方式放置

    Spinner.js

    import styled from 'styled-components';
    
    export const StyledSpinner = styled.svg`
     animation: rotate 1s linear infinite;
     width: 50px;
     height: 30px;
    
     & .path {
      stroke: ${({ colorValue }) => colorValue}; // color props 
      stroke-linecap: round;
      animation: dash 1.5s ease-in-out infinite;
     }
    
     @keyframes rotate {
       100% {
         transform: rotate(360deg);
       }
     }
     @keyframes dash {
       0% {
         stroke-dasharray: 1, 150;
         stroke-dashoffset: 0;
       }
       50% {
         stroke-dasharray: 90, 150;
         stroke-dashoffset: -35;
       }
       100% {
         stroke-dasharray: 90, 150;
         stroke-dashoffset: -124;
       }
     }
    `;
    
    const Spinner = ({ colorValue }) => (
      <StyledSpinner viewBox="0 0 50 50" colorValue={colorValue}>
        <circle
         className="path"
         cx="25"
         cy="25"
         r="20"
         fill="none"
         strokeWidth="4"
       />
     </StyledSpinner>
    );
    
    export default Spinner;
    

    NewComponent.js

    import Spinner from '../Spinner';
    
    const CustomSpiners = () => (
      <Spinner colorValue="white" />
      <Spinner colorValue="red" />
    );
    
    export default CustomSpiner
    

    【讨论】:

    • 我不想导入&lt;circle ..。再次。那将是多余的
    • 我确实更新了代码,认为这种方法是你想要的。我确实在 styled-component 中使用了道具来将可变颜色放入笔画中。 reference
    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2021-03-08
    • 2021-09-06
    • 2019-12-14
    • 2020-12-01
    • 2019-04-12
    • 2021-11-01
    相关资源
    最近更新 更多