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

犬猫スイッチ

Last updated at Posted at 2020-08-09

以下の画像のようなものをイメージに作ります.
image.png

#STEP1 ボタンの作成
App.jsとapp.cssを用意し,その中に以下のプログラムを入力し,ボタンを作成する

###App.js

import React, {Component} from 'react';
import './app.css';

class App extends Component{
  render(){
    return(
      <div>
        <h1></h1>
        <div className='buttons'>
          <button></button>
          <button></button>
        </div>
      </div>
    );
  }
}
export default App

###app.css

h1{
  text-align: center;
}

.buttons {
  margin-top: 40px;
  padding: 0;
  font-family: sans-serif;
  text-align: center;
}

button {
  display: inline-block;
  font-size: 16px;
  width: 200px;
  height: 48px;
  border-radius: 48px;
  margin-right: 24px;
  margin-left: 24px;
  color: #fff;
  background-color: #66ccff;
  border: none;
  outline: none;
  box-shadow: 4px 4px #d8d8d8;
  cursor: pointer;
}

button:active {
  position: relative;
  top: 4px;
  left: 4px;
  box-shadow: none;
}

すると
image.png

ができました.

#STEP2 犬と猫の表示切り替え
犬と猫のボタンを押すことでStateを更新して表示させます.

###初期状態の定義
constructorとsuperで構成される定番の形の中でstateを定義します.
そしてstateを表示させるために<h1>犬</h1><h1>{}</h1>

class App extends Component{
  constructor(){
    super();
    this.state={name: '犬or猫'}
  }
  render(){
    return(
      <div>
        <h1>{this.state.name}</h1>
  省略
}

image.png

###ボタンの実装

handleClick=()=>{処理}をベースにボタンを以下のように実装しました.

handleDogClick=()=>{
    this.setState({name:''});
  }
  handleCatClick=()=>{
    this.setState({name:''});
  }

省略

   <button onClick={this.handleDogClick}></button>
   <button onClick={this.handleCatClick}></button>

# 完成

import React, {Component} from 'react';
import './app.css';

class App extends Component{
  constructor(){
    super();
    this.state={name: '犬or猫'}
  }
  
  handleDogClick=()=>{
    this.setState({name:''});
  }
  handleCatClick=()=>{
    this.setState({name:''});
  }


  render(){
    return(
      <div>
        <h1>{this.state.name}</h1>
        <div className='buttons'>
          <button onClick={this.handleDogClick}></button>
          <button onClick={this.handleCatClick}></button>
        </div>
      </div>
    );
  }
}
export default App
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?