3
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 5 years have passed since last update.

【REACT】stateを学びましょう!

Last updated at Posted at 2020-03-20

概要

stateを理解し、使って見ましょう!

state?

REACTでstateは、Component内部で変えることができる値
REACTには、二種類のstateがあります。

  • class型Componentが持っているstate
  • 関数型ComponentでuseStateという関数で使うstate

class型Component

create-react-app
https://codesandbox.io/?from-app=1
で、projectを作成しましょう

簡単な数字カウンター

count.js
import React, { Component } from "react";

class Count extends Component {
  constructor(props) {
    super(props);
    // stateの初期値を設定
    this.state = {
      number: 0
    };
  }

  render() {
    // stateを呼ぶとき使う
    const { number } = this.state;
    return (
      <div>
        <h1>{number}</h1>
        <button
          onClick={() => {
            // setStateを使って、stateに新しいvalueを設定
            this.setState({ number: number + 1 });
          }}
        >
          +1
        </button>
      </div>
    );
  }
}

export default Count;

結果

関数型Component

Hi & Good bye

Say.js
import React, { useState } from "react";

const say = () => {
  const [message, setMessage] = useState("");
  const onClickEnter = () => setMessage("Hello");
  const onClickLeave = () => setMessage("Good Bye");

  return (
    <div>
      <button onClick={onClickEnter}>Enter</button>
      <button onClick={onClickLeave}>Leave</button>
      <h1>{message}</h1>
    </div>
  );
};

export default say;

結果

問題

【Red】、【Blue】ボタンを追加して、ボタンをクリックしたら、
<h1>{message}</h1>の messageの色が変わるようにしましょう!

hint
styleを使いましょう!

正解

3
0
1

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