簡體   English   中英

React 中樣式化組件的可重用性

[英]Reusability with Styled-Components in React

我需要在其他組件中使用我的自定義微調器。 所以我做了一個可重復使用的微調器? 如何復制其樣式並自定義其他樣式? 我只想改變加載的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

新組件.js

import CustomSpinner from '../Spinner'

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

您可以在 Spiner.js 組件中添加自定義樣式,然后將其導出。 在 NewComponent.js 中,您導出自定義微調樣式並像在 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;

新組件.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