StyledComponentを使ってCSSアニメーションを作る時に使うkeyframes
に引数を渡して動的にアニメーションを調整する方法を、忘備録として。
結論
こんな感じ。
import { keyframes } from 'styled-components'
export const zoomInToAnyScale = (num: number) =>
keyframes`
from { transform: scale(0) }
to { transform: scale(${num}) }
`
const StyledDiv = styled.div`
animation: ${zoomInToAnyScale(3)} 0.3s ease 0.5s forwards;
`
const ZoomInDiv = styled.div<{ scale: nuber }>`
animation: ${({scale}) => zoomInToAnyScale(scale) } 0.3s ease 0.5s forwards;
`
環境
一応、環境はこんな感じ。
package | version |
---|---|
React | 16.13.0 |
StyledComponents | 5.0.1 |
TypeScript | 3.8.3 |
解説
(解説というほどのものでもないけど)
StyledComponentsで宣言するkeyframes
は元はただの関数です。引数にとるのはTemplateStringsArray | CSSKeyframes
となっていますが、要はCSSが書かれた文字列orオブジェクトなので、こんな書き方もできます。
import { keyframes } from 'styled-components'
export const zoomInToAnyScale = (num: number) => {
return keyframes({
from: { transform: `scale(0)` },
to: { transform: `scale(${num})` }
})
つまりは、テンプレートリテラルなどに埋めてそのまま引数として渡せばいいだけ。
ちなみにstyled.div
などはただの関数もうちょっと複雑になってるようです。
終わりに
最近CSSアニメーションに夢中になって、いろいろな作品を見て「すげええええ」って言いながら勉強しています。
いや、本当にすごいんですよ。CSSアニメーターの方全員尊敬してます。神。
StyledComponents自体の記事は多いのですが、keyframesはあまり見かけなかったので書いてみました。
実務とかだと、ただのCSSアニメーションは扱いづらいのかもしれないですね。
トリガーで発火させるようなアニメーションは、JS側で管理しやすいreact-springとかの方が良さそうです。