LoginSignup
0
0

More than 1 year has passed since last update.

React: State の使い方

Last updated at Posted at 2022-06-28

こちらを参考にしました。

React State

プロジェクトの作成

create-react-app re02
cd re02
yarn start

src/App.js を次で置き換えます。

src/App.js
import './App.css';
import React from 'react';

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }

  changeColor = () => { this.setState({color: "blue"}); }
  changeGreen = () => { this.setState({color: "green"}); }
  changeRed = () => { this.setState({color: "red"}); }

  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
        <button type="button" onClick={this.changeColor} >Change color</button>
	&nbsp;
        <button type="button" onClick={this.changeGreen} >Change Green</button>
	&nbsp;
        <button type="button" onClick={this.changeRed} >Change Red</button>
      </div>
    );
  }
}

function App() {
  return (
    <div className="App">
      <header className="App-header">
	<p>Hello World!</p>
	<Car />
	<blockquote>
	<p>Jun/28/2022</p>
	</blockquote>
      </header>
    </div>
  );
}

export default App;

ブラウザーで、 http://localhost:3000/ にアクセス
image.png

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