본문 바로가기

React

state 변형

import React, {Componentfrom 'react';

 

class Counter extends React.Component {

    constructor(props) {

        super(props);

        this.state = {

            number: 0

        }

        this.cntIncrease = this.cntIncrease.bind(this);

        this.cntDecrease = this.cntDecrease.bind(this);

    }

 

    cntIncrease() {

        this.setState({

            number: this.state.number + 1

        })

    }

 

    cntDecrease() {

        this.setState({

            number: this.state.number - 1

        })

    }

 

    render() {

        return (

            <>

                <h1>{this.state.number}</h1>

                <button onClick={this.cntIncrease}>+ 버튼</button>

                <button onClick={this.cntDecrease}>- 버튼</button>

            </>

        )

    }

 

}

 

export default Counter;

 

 

=========================================

 

import React, {Componentfrom 'react';

 

class Counter extends React.Component {

    constructor(props) {

        super(props);

        this.state = {

            number: 0

        }

    }

 

  

cntIncrease() {

        this.setState(

            {

                number: this.state.number + 1

            },

            () => {

                alert('counter: ' + this.state.number);

            }

        )

    }

 

    render() {

        const {number} = this.state;

        return (

            <>

                <h1>{number}</h1>

                <button onClick={() => this.cntIncrease()}>

                    + 버튼

                </button>               

            </>

        )

    }

 

}

 

export default Counter;

'React' 카테고리의 다른 글

hooks  (0) 2021.03.11
state  (0) 2021.03.09