質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.47%
TypeScript

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

CSS

CSSはXMLやHTMLで表現した色・レイアウト・フォントなどの要素を指示する仕様の1つです。

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

Q&A

解決済

1回答

139閲覧

ReactでCSSアニメーションを使ったときに初期レンダー時にアニメが発動してしまう問題

退会済みユーザー

退会済みユーザー

総合スコア0

TypeScript

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

CSS

CSSはXMLやHTMLで表現した色・レイアウト・フォントなどの要素を指示する仕様の1つです。

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

0グッド

1クリップ

投稿2024/04/21 17:35

実現したいこと

以下のようなReactアプリを作成したいです。

  • 縦横300ピクセルの正方形の中に横長の長方形が表示される。(長方形の高さは48ピクセルで、色は黒)
  • 長方形の中心と正方形の中心は一致する。(この場合、中心とは各図形の対角線の交点を意味します)
  • 初期表示のとき、長方形の長いほうの辺は水平方向の向き
  • 正方形のどこかをクリックすると、長方形は中心の周りに時計回りで90度回転する
  • もう一度、正方形のどこかをクリックすると、長方形は中心の周りに反時計回りで90度回転して元の水平の向きに戻る。
  • 以後、正方形のどこかをクリックすると上記を交互に繰り返す。
  • 長方形は回転する間に以下のようなアニメーションをする。アニメーション全体の時間を1.5秒とする。
    • 正方形がクリックされたと同時に長方形の色は赤に変わる。
    • 赤に変わってから90度回転する。回転に要する時間をアニメ全体の時間の70%とする。
    • 回転が完了してから残りの30%の時間を使って長方形の色を赤から黒に戻す。

発生している問題・分からないこと

  • 以下のコマンド
npx create-react-app@latest sample-app --template typescript

で、sample-app というアプリを作った後、sample-app/src/App.tsx を修正していきました。

  • 現状では「該当のソースコード」のものになっており、ほぼ出来ているのですが一点問題があります。

  • 問題は、以下の動画のようにブラウザをリロードさせると横棒が初期表示の水平方向に置かれた状態に収まるまでにアニメーションしてしまうことです。

イメージ説明

  • 現状では上の画像のように初期表示のときにアニメーションが発生しますが、これを抑止して初めから水平方向に黒い棒が表示されるようになる修正方法を調べていますが分かっていません。

  • ご教示いただきたいのは以下の2点です。

    • (1) なぜ初期表示のときにアニメーションが発生してしまうのか
    • (2) どのように修正すると初期表示のときのアニメーションを抑止できるのか

よろしくお願いいたします。

該当のソースコード

Typescript

1import { PropsWithChildren, useState } from 'react' 2 3type Position = 'absolute' | 'relative' 4type Direction = 'horizontal' | 'vertical' 5 6const anotherDirection: Record<Direction, Direction> = { 7 horizontal: 'vertical', 8 vertical: 'horizontal' 9} as const 10 11const spanStyleBase = { 12 width: '100%', 13 height: '48px', 14 display: 'inline-block', 15 position: 'absolute' as Position, 16 transform: 'translate(0, -50%)', 17 top: '50%', 18 backgroundColor: 'black', 19 20 /* animation settings */ 21 animationDuration: '1.5s', 22 animationFillMode: 'forwards', 23 animationDirection: 'normal' 24} 25 26const divStyle = { 27 width: 300, 28 height: 300, 29 position: 'relative' as Position, 30 cursor: 'pointer', 31 backgroundColor: '#eee' 32} 33 34const cssKeyframes = ` 35 36 @keyframes rotate-to-vertical { 37 0% { 38 background-color: red; 39 transform: translate(0, -50%) rotate(90deg); 40 } 41 70% { background-color: red; } 42 100% { background-color: black; } 43 } 44 45 @keyframes rotate-to-horizontal { 46 0% { background-color: red; } 47 70% { 48 background-color: red; 49 transform: translate(0, -50%) rotate(90deg); 50 } 51 100% { 52 background-color: black; 53 transform: translate(0, -50%) rotate(90deg); 54 } 55 } 56` 57 58const RotatableLine = ({ direction, onClick }: { direction: Direction; onClick: () => void }) => { 59 const spanStyle = { 60 ...spanStyleBase, 61 animationName: `rotate-to-${anotherDirection[direction]}` 62 } 63 return ( 64 <div style={divStyle} onClick={onClick}> 65 <span style={spanStyle} /> 66 </div> 67 ) 68} 69 70const Container = ({ children }: PropsWithChildren) => 71 <div style={{ display: 'flex', justifyContent: 'center', marginTop: 50 }}>{children}</div> 72 73 74export default function App() { 75 const [direction, setDirection] = useState<Direction>('horizontal') 76 77 const handleToggleDirection = () => { 78 setDirection((state) => anotherDirection[state]) 79 } 80 81 return ( 82 <Container> 83 <style>{cssKeyframes}</style> 84 <RotatableLine direction={direction} onClick={handleToggleDirection} /> 85 </Container> 86 ) 87} 88

試したこと・調べたこと

  • teratailやGoogle等で検索した
  • ソースコードを自分なりに変更した
  • 知人に聞いた
  • その他
上記の詳細・結果

調べましたが分かりませんでした。

補足

特になし

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

juner

2024/04/22 00:48

そのコードを見た限り、 最初から animationName を指定している様に見えるのですが、これは意図しているのでしょうか?(設定されていれば初期状態からアニメーションしませんでしょうか?
退会済みユーザー

退会済みユーザー

2024/04/22 01:41

コメントありがとうございます。 はい。 > 最初から animationName を指定して いますが、これによって初期表示のときもアニメーションされるという理解ができておりませんでした。 つまり「現状のコードで初期表示ではアニメーションされないだろう」という思い込みがあり、それは多分、cssによるanimation 設定の基本知識の何かが足りてないせいだと思うのですが、その何かが何なのかが分かっていない気がしています。 ですので「MDNのこのへんちゃんと読め」的なご指摘でもありがたいです。
guest

回答1

0

ベストアンサー

css の animation-name property は 設定した段階でそのアニメーションが再生される為、この 場合初期表示時点でそれが実施されるものと思われます。

https://developer.mozilla.org/ja/docs/Web/CSS/animation-name

https://developer.mozilla.org/ja/docs/Web/CSS/CSS_animations/Using_CSS_animations

もしも要素のアニメーションをjsで動的にやりたい場合は class の追加・削除等で css の animation-name を設定する他に Element#animate() を使う方法もあります。

https://developer.mozilla.org/ja/docs/Web/API/Element/animate

https://developer.mozilla.org/ja/docs/Web/API/Web_Animations_API

以上。

追伸:
参考まで css animation と js animation(Web Animation API) の比較サンプルを追記しておきます。

playground

html

1 2<div class="css"> 3 <h1>css</h1> 4 <h2>表示時</h2> 5 <div class="target case-1"></div> 6 <h2>hover時</h2> 7 <div class="target case-2"></div> 8 <h2>click時</h2> 9 <div class="target case-3"></div> 10</div> 11<div class="js"> 12 <h1>js</h1> 13 <h2>表示時</h2> 14 <div class="target case-1"></div> 15 <h2>hover時</h2> 16 <div class="target case-2"></div> 17 <h2>click時</h2> 18 <div class="target case-3"></div> 19</div> 20<script type=module> 21 const keyframes = [ 22 { transform: 'rotate(0)'}, 23 { transform: 'rotate(1turn)'}, 24 ]; 25 const options = { 26 duration: 1000, 27 iterations: Infinity, 28 }; 29 const onetime = { 30 duration: 1000, 31 iterations: 1, 32 }; 33 { 34 // js 表示時 35 const target = document.querySelector(".js .target.case-1"); 36 target.classList.add('animate'); 37 target.animate(keyframes, options); 38 } 39 { 40 // js hover時 41 let controller = new AbortController(); 42 const target = document.querySelector(".js .target.case-2"); 43 target.addEventListener('pointerover', (e) => { 44 const target = e.currentTarget; 45 target.setPointerCapture(e.pointerId); 46 target.classList.add('animate'); 47 const animate = target.animate(keyframes, options); 48 const signal = controller.signal; 49 signal.addEventListener('abort', () => { 50 target.classList.remove('animate'); 51 animate.cancel(); 52 }) 53 }); 54 target.addEventListener('pointerout', (e) => { 55 controller.abort(); 56 controller = new AbortController(); 57 }); 58 } 59 { 60 // js click時 61 let controller = new AbortController(); 62 const target = document.querySelector(".js .target.case-3"); 63 target.addEventListener('pointerup', async (e) => { 64 const target = e.currentTarget; 65 66 // 前をキャンセル 67 controller.abort(); 68 const c = new AbortController(); 69 controller = c; 70 71 const animate = target.animate(keyframes, onetime); 72 const signal = c.signal; 73 // キャンセルすると状態をクリアする 74 signal.addEventListener('abort', () => { 75 target.classList.remove('animate'); 76 if (animate.playState === "finished") return; 77 animate.cancel(); 78 }); 79 target.classList.add('animate'); 80 try { 81 await animate.finished; 82 }catch(e){ } 83 // 完了したので状態をクリアする 84 c.abort(); 85 }); 86 } 87 { 88 // css click時 89 let controller = new AbortController(); 90 const target = document.querySelector(".css .target.case-3"); 91 let promise = Promise.resolve(); 92 let i = 0; 93 target.addEventListener('pointerup', (e) => { 94 const target = e.currentTarget; 95 96 // 前をキャンセル 97 controller.abort(); 98 const c = new AbortController(); 99 controller = c; 100 101 // シーケンシャルに実行しないと タイミングに問題が出る 102 promise = promise.then(async () => { 103 target.classList.add('animate'); 104 const signal = c.signal; 105 106 // キャンセル時は class を外すだけ 107 signal.addEventListener('abort', () => { 108 target.classList.remove('animate'); 109 }); 110 111 const deferred = (() => { 112 let resolve,reject; 113 const promise = new Promise((res, rej) => [resolve, reject] = [res,rej]); 114 return {resolve, reject, promise}; 115 })(); 116 117 // animationend / animationcancel どちらかが発生するまで待機 118 target.addEventListener('animationend', deferred.resolve); 119 target.addEventListener('animationcancel', deferred.resolve); 120 await deferred.promise; 121 122 // キャンセルしていなければ キャンセル 123 if (!signal.aborted) c.abort(); 124 // イベントの解放 125 target.removeEventListener('animationend', deferred.resolve); 126 target.removeEventListener('animationcancel', deferred.resolve); 127 }); 128 }); 129 } 130</script> 131<style> 132 :root { 133 --animate-color: red; 134 .target { 135 height: 100px; 136 width: 100px; 137 display:inline-block; 138 background-color: green; 139 } 140 .js { 141 .animate { 142 background: var(--animate-color); 143 } 144 } 145 .css { 146 /* css 常時 */ 147 .case-1 { 148 background: var(--animate-color); 149 animation: linear 1000ms infinite normal rotate; 150 } 151 /* css hover時 */ 152 .case-2:hover { 153 background: var(--animate-color); 154 animation: linear 1000ms infinite normal rotate; 155 } 156 .case-3.animate { 157 background: var(--animate-color); 158 animation: linear 1000ms 1 normal rotate; 159 } 160 } 161 } 162 @keyframes rotate { 163 from { 164 transform: rotate(0); 165 } 166 167 to { 168 transform: rotate(1turn); 169 } 170 } 171</style> 172<style> 173 /* あまり関係ないその他のスタイル */ 174 :root { 175 body { 176 display:grid; 177 grid-template-columns: min-content min-content; 178 grid-auto-flow: row; 179 gap: 20px; 180 } 181 .js, .css { 182 display: grid; 183 grid-auto-flow: row; 184 grid-row: 1 / -1; 185 } 186 .js { 187 grid-column: 1; 188 & > * { 189 grid-column: 1; 190 } 191 } 192 .css { 193 grid-column: 2; 194 & > * { 195 grid-column: 2; 196 } 197 } 198 } 199</style>

投稿2024/04/22 02:37

編集2024/04/22 08:47
juner

総合スコア128

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2024/04/22 02:44

ありがとうございます。ご提示のMDNのページを熟読して出直します。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.47%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問