2swan

버튼 증가,감소 본문

Programming/React

버튼 증가,감소

2swan 2023. 9. 1. 10:47

Device.js

import logo from './logo.svg';
import './App.css';
import Device from './Device';
import Counter from './Counter';

function App() {
 
  return(
    <div>
      <h1>안녕</h1>
      <h2>안녕2</h2>
      <Device />
      <Counter/>
    </div>
  );

}

export default App;

 

App.js

import logo from './logo.svg';
import './App.css';
import Device from './Device';
import Counter from './Counter';
import Food from './food';

function App() {
 
  return(
    <div>
      <h1>안녕</h1>
      <h2>안녕2</h2>
      <Device />
      <Counter/>
    </div>
  );

}

export default App;

 

Counter.js

import { Component } from "react";

class Counter extends Component{
  constructor(props){
      super(props);
      this.state = {
        count : 0
      }
      this.increaseCount = this.increaseCount.bind(this);
      this.decreaseCount = this.decreaseCount.bind(this);
  }

  //증가
  increaseCount(){
    this.setState(({count})=>{
      return{
        count : count +1
      }
    });
  }

  //감소
  decreaseCount(){
    // this.setState(({count})=>{
    //   return{
    //     count : count -1
    //   }
    // });
    this.setState((st)=>{
      console.log("st :" + st.count)
      return{
        count :st.count-1
      }
    });
  }


  render(){
    return(
      <div>
        <span>카운트 : {this.state.count}</span>
        <button onClick={this.increaseCount}>카운트 증가</button>
        <button onClick={this.decreaseCount}>카운트 감소</button>
      </div>
    )
  }
}

export default Counter;

 

 

'Programming > React' 카테고리의 다른 글

React Practice(4-3)  (0) 2023.09.04
React Practice(4-2)  (0) 2023.09.04
React Practice(4-1)  (1) 2023.09.04
React 클래스형, 함수형  (0) 2023.09.04
React 설치  (0) 2023.09.01