1
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.

Reactでおみくじ作成(javascript版あり)

Last updated at Posted at 2022-01-15

画面収録-2022-01-15-18.53.24.gif
React自主トレ中です。
javascriptで作成したおみくじをReactで再現して同じ動作ができるようにします。

hooksは私が仕事してた頃は使ってなかったので
ゼロから調べました。

github
https://github.com/mhosokawa2021/omikuji_react

#まずはサクッとjavascript

omikuji_js.html
    <p id="btn">おみくじを引く</p>
    <script>
        'use strict';
        var btn = document.getElementById('btn');

          btn.addEventListener('click', function () {
                var n = Math.ceil(Math.random() * 5);
                if (n == 1) {
                    this.textContent = '大吉';
                } else if (n == 2) {
                    this.textContent = '';
                } else if (n == 3) {
                    this.textContent = '中吉';
                } else if (n == 4) {
                    this.textContent = '小吉';
                } else if (n == 5) {
                    this.textContent = '';
                }
            });
            
    </script>

cssで少し見た目を整えます。

omikuji_js.html
#btn{
      font-size: 13px;
      background-color: #ccc;
      cursor: pointer;
      text-align: center;
    }

#Reactで挙動を再現する その1
とりあえず見た目だけ移植。

index.js
  import ReactDOM from "react-dom";
  import { App } from "./App";

  ReactDOM.render(<App />, document.getElementById("root"));
app.jsx
import React from "react";
import "./styles.css";

export const App = () => {
  return (
    <>
      <p className="btn">おみくじを引く</p>
    </>
  );
};
style.css
.btn{
      font-size: 13px;
      background-color: #ccc;
      cursor: pointer;
      text-align: center;
    }

#Reactで挙動を再現する その2

動きの部分の処理を追加していきます。
(jsxのみ更新したのでそこだけ)

app.jsx
import React, { useState } from "react";
import "./styles.css";

export const App = () => {
  const [omikuji, setOmikuji] = useState("おみくじを引く");
  const onClickOmikuji = () => {
    var arr = ["大吉", "小吉", "中吉", "", "", "大凶"];
    var index = Math.floor(Math.random() * arr.length);
    setOmikuji(arr[index]);
  };
  return (
    <>
      <p className="btn" onClick={onClickOmikuji}>
        {omikuji}
      </p>
    </>
  );
};

できました。
画面収録-2022-01-15-18.53.24.gif

##参考
https://ja.reactjs.org/docs/hooks-reference.html

1
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
1
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?