LoginSignup
0
0

More than 1 year has passed since last update.

基礎から学ぶReact/React Hooks学習メモ 5-1 useState

Last updated at Posted at 2021-09-09

React Hooksを基礎から理解する 5-1 useState

参考
- 基礎から学ぶReact/React Hooks

useState

  • インポートする
    • import React, { useState} from 'react'
  • useStateの基本構文
    • const [状態変数, 状態を変更するための変数] = useState(状態の初期値)

image.png

Counter.js
import "./styles.css";

export const Counter = ({
  count,
  countIncrement,
  countDecrement,
  countReset,
  initialCount
}) => {
  return (
    <div>
      <p>
        現在のカウント数{count}
        <br />
        countの初期値{initialCount}
      </p>
      <button onClick={countIncrement}>Increment</button>
      <button onClick={countDecrement}>Decrement</button>
      <button onClick={countReset}>Reset</button>
    </div>
  );
};
Hello.js
import "./styles.css";

export const Hello = ({ name, handleChangeName, initialName }) => {
  return (
    <div>
      <p>
        Hello, <b>{name} !!</b>
        <br />
        nameの初期値 <b>{initialName}</b>
      </p>
      <input type="text" onChange={handleChangeName} />
    </div>
  );
};
App.js
import React, { useState } from "react";

// 名前付きインポート
import { Hello } from "./Hello";
import { Counter } from "./Counter";

const INITIAL_COUNT = 0;
const INITIAL_NAME = "JavaScript";

export default function App() {
  // useState初期化
  const [count, setCount] = useState(INITIAL_COUNT);
  const [name, setName] = useState(INITIAL_NAME);

  // countボタンのイベントハンドラ setCount((c) => c+1) で引数に現在の値が入ってくる
  const countIncrement = () => setCount((prevCount) => prevCount + 1);
  const countDecrement = () => setCount((prevCount) => prevCount - 1);
  const countReset = () => setCount(INITIAL_COUNT);

  // テキストボックスのイベントハンドラ
  const handleChangeName = (e) => {
    setName(e.target.value);
  };

  return (
    <>
      <Counter
        count={count}
        countIncrement={countIncrement}
        countDecrement={countDecrement}
        countReset={countReset}
        initialCount={INITIAL_COUNT}
      />
      <Hello
        name={name}
        handleChangeName={handleChangeName}
        initialName={INITIAL_NAME}
      />
    </>
  );
}
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