0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Next.js (React) でエンターを押し続けると色が薄まっていくコード例

Posted at

ポイント

  • エンターキーを押すたびに 0から +1 ずつ数値をカウントアップする
  • 数値を3つ繋げて16進数に直すとカラーコードになる ( 例: #999999 )
  • カラーコードを css の color として利用する

コード

pages/ColorIncrement.tsx

import React, { useEffect, useState } from 'react';

const ColorIncrement = () => {
  const [count, setCount] = useState(0);
  const handleKeyDownEnter = (event: KeyboardEvent) => {
    if (event.key === "Enter") {
      setCount(count + 1);
      console.log("Enter")
    }
  };

  useEffect(() => {
    document.addEventListener("keydown", handleKeyDownEnter);
    return () => {
      document.removeEventListener("keydown", handleKeyDownEnter);
    };
  }, [count]);

  var color_flagment = ( '00' + count.toString(16) ).slice( -2 );

  var color = '#' + color_flagment + color_flagment + color_flagment
  var style = {color: color, background: "white", fontSize: "50pt"}
  return <div style={style}>{color}</div>
}

export default ColorIncrement

表示例

image
image
image

環境

next@13.1.1

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?