简体   繁体   English

React 中样式化组件的可重用性

[英]Reusability with Styled-Components in React

I need to use my custom spinner in other components.我需要在其他组件中使用我的自定义微调器。 So I made a reusable spinner?所以我做了一个可重复使用的微调器? How do I copy its styles and customize other styles?如何复制其样式并自定义其他样式? I want to change just the stroke or the color of the loading.我只想改变加载的stroke或颜色。 Pls check my code here请在这里检查我的代码

Spinner.js 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新组件.js

import CustomSpinner from '../Spinner'

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

You can add custom style inside the Spiner.js component and then export that.您可以在 Spiner.js 组件中添加自定义样式,然后将其导出。 In NewComponent.js you export custom spiner style and put it same way like in Spiner.js在 NewComponent.js 中,您导出自定义微调样式并像在 Spiner.js 中一样放置它

Spinner.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新组件.js

import Spinner from '../Spinner';

const CustomSpiners = () => (
  <Spinner colorValue="white" />
  <Spinner colorValue="red" />
);

export default CustomSpiner

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM