Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8725

【StyledComponent + CSSアニメーション】keyframesに引数をつける

$
0
0

StyledComponentを使ってCSSアニメーションを作る時に使うkeyframesに引数を渡して動的にアニメーションを調整する方法を、忘備録として。

結論

こんな感じ。

keyframes
import{keyframes}from'styled-components'exportconstzoomInToAnyScale=(num:number)=>keyframes`
    from { transform: scale(0) }
    to { transform: scale(${num}) }
  `
使い方
constStyledDiv=styled.div`
  animation: ${zoomInToAnyScale(3)} 0.3s ease 0.5s forwards;
`constZoomInDiv=styled.div<{scale:nuber}>`
  animation: ${({scale})=>zoomInToAnyScale(scale)} 0.3s ease 0.5s forwards;
`

環境

一応、環境はこんな感じ。

packageversion
React16.13.0
StyledComponents5.0.1
TypeScript3.8.3

解説

(解説というほどのものでもないけど)
StyledComponentsで宣言するkeyframesは元はただの関数です。引数にとるのはTemplateStringsArray | CSSKeyframesとなっていますが、要はCSSが書かれた文字列orオブジェクトなので、こんな書き方もできます。

keyframes
import{keyframes}from'styled-components'exportconstzoomInToAnyScale=(num:number)=>{returnkeyframes({from:{transform:`scale(0)`},to:{transform:`scale(${num})`}})

つまりは、テンプレートリテラルなどに埋めてそのまま引数として渡せばいいだけ。
ちなみにstyled.divなどはただの関数もうちょっと複雑になってるようです。

終わりに

最近CSSアニメーションに夢中になって、いろいろな作品を見て「すげええええ」って言いながら勉強しています。
いや、本当にすごいんですよ。CSSアニメーターの方全員尊敬してます。神。

StyledComponents自体の記事は多いのですが、keyframesはあまり見かけなかったので書いてみました。
実務とかだと、ただのCSSアニメーションは扱いづらいのかもしれないですね。

トリガーで発火させるようなアニメーションは、JS側で管理しやすいreact-springとかの方が良さそうです。


Viewing all articles
Browse latest Browse all 8725

Latest Images

Trending Articles

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>