簡體   English   中英

動畫 SVG 圖標作為 React JS 中的組件

[英]Animated SVG icon as a Component in React JS

我正在嘗試將此動畫 SVG 作為 React JS 中的一個組件,但我找不到解決方案。

如果可能,我想避免將所有樣式移動到單獨的 .css 文件中。 如何在 React JS 中將 SVG 作為組件導入但保留所有樣式?

SVG

<svg class="spinner" width="150" height="150" viewBox="0 0 100 100">
      <circle class="background" r="24" cx="50" cy="50"></circle>
      <path
        class="line"
        d="M 37.5,50 C 37.5,43.096441 43.096441,37.5 50,37.5 C 56.903559,37.5 62.5,43.096441 62.5,50 C 62.5,56.903559 56.903559,62.5 50,62.5 C 43.096441,62.5 37.5,56.903559 37.5,50"
      ></path>
    </svg>

CSS

body {
  align-items: center;
  background: #333;
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100vh;
}
.background {
  fill: #555;
}
.line {
  animation: PacMan 5s infinite;
  fill: none;
  stroke: #d26188;
  stroke-width: 25;
}
.spinner {
  animation: Spin 2s infinite linear;
}
@keyframes PacMan {
  0% {
    stroke-dasharray: 79px 79;
  }
  50% {
    stroke-dasharray: 1px 79;
  }
  100% {
    stroke-dasharray: 79px 79;
  }
}
@keyframes Spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

您也可以在組件內內聯樣式。 樣式應該是一個字符串(因為文本是多行的,所以用反引號換行),所以 React 不會嘗試將大括號解析為表達式。

注意:嵌入在樣式中的類名會影響頁面上的所有內容,因此您應該添加一個命名空間,或者以其他形式使它們唯一。

 const Spinner = () => ( <React.Fragment> <style> {` .spinner .background { fill: #555; } .spinner .line { animation: PacMan 5s infinite; fill: none; stroke: #d26188; stroke-width: 25; } .spinner .spinner { animation: Spin 2s infinite linear; } @keyframes PacMan { 0% { stroke-dasharray: 79px 79; } 50% { stroke-dasharray: 1px 79; } 100% { stroke-dasharray: 79px 79; } } @keyframes Spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } `} </style> <svg class="spinner" width="150" height="150" viewBox="0 0 100 100"> <circle class="background" r="24" cx="50" cy="50"></circle> <path class="line" d="M 37.5,50 C 37.5,43.096441 43.096441,37.5 50,37.5 C 56.903559,37.5 62.5,43.096441 62.5,50 C 62.5,56.903559 56.903559,62.5 50,62.5 C 43.096441,62.5 37.5,56.903559 37.5,50" ></path> </svg> </React.Fragment> ) ReactDOM.render( <Spinner />, root )
 body { align-items: center; background: #333; display: flex; flex-direction: column; justify-content: center; height: 100vh; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM