[Reacte] Event setState ํ•จ์ˆ˜

2021. 10. 2. 08:01ใ†Front-End ์ž‘์—…์‹ค/Vue.js

728x90
๋ฐ˜์‘ํ˜•

 

 

 

๐Ÿ“Œ Event setState ํ•จ์ˆ˜ ์ดํ•ดํ•˜๊ธฐ


๋ฐ˜์‘ํ˜•
return (
            <div className="App">
                {/* Stateํ™” ํ•˜๊ธฐ ์ „ ์ฝ”๋“œ */}
                {/*<Subject title="WEB" sub="word wide web!"></Subject>*/}

                {/*Stateํ™” ํ•œ ๋’ค ์ฝ”๋“œ*/}
                {/*<Subject title={this.state.subject.title} sub={this.state.subject.sub}></Subject>*/}

                <header>
                    <h1><a href ="/" onClick={function (e) {
                        // this.state.mode = 'welcome'
                        this.setState({
                            mode:'welcome'
                        });
                    }.bind(this)}>{this.state.subject.title}</a></h1>
                    {this.state.subject.sub}
                </header>

                <Nav data = {this.state.contents}> </Nav>
                <Content title={_title} desc={_desc}> </Content>
            </div>

 

์œ„์™€ ๊ฐ™์€ ์ฝ”๋“œ์—์„œ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์ด๋ฏธ ์ƒ์„ฑ๋œ ์ดํ›„์— [this.state.mode = 'welcome']์ฒ˜๋Ÿผ State ๊ฐ’์„ ์ง์ ‘ ๋ณ€๊ฒฝํ•˜๋ฉด ์•ˆ๋˜๊ณ , ํ•จ์ˆ˜ ํ˜•ํƒœ๋กœ ๋ณ€๊ฒฝํ•ด์•ผ ํ•˜๋Š” ์ด์œ ๋ฅผ ์•Œ์•„๋ณผ ๊ฒƒ์ด์—์š”.

 

 constructor(props) {
        // State ๊ฐ’์„ ์ดˆ๊ธฐํ™” ์‹œํ‚ค๊ธฐ ์œ„ํ•จ์ด๊ณ , ๊ทธ ์ดˆ๊ธฐ๊ฐ’์œผ๋กœ 'title="WEB" sub="word wide web!"'์„ ์„ค์ •ํ•˜๋ ค ํ•œ๋‹ค.
        super(props);
        this.state = {
            mode : 'read',
            subject:{title:'Web', sub:'World Wide Web!'},
            welcome : {title:'Welcome', desc : 'Hello, React!!!'},
            contents: [
                {id:1, title:'HTML', desc: 'HTML is for information'},
                {id:2, title:'CSS', desc: 'CSS is for desing'},
                {id:3, title:'JavaScript', desc: 'JavaScript is for interative'}
            ]
        }
    } // constructor() ๋

 

๋จผ์ € ์œ„์—์„œ ์ƒ์„ฑ์ž๊ฐ€ App์ด๋ผ๋Š” ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์ƒ์„ฑ๋  ๋•Œ ๊ฐ€์žฅ ๋จผ์ € ์‹คํ–‰๋˜๋Š” 
Constructor์—์„œ๋Š” this.state = { ... }์™€ ๊ฐ™์ด ์ด๋Ÿฐ์‹์œผ๋กœ ์„ค์ •ํ•˜๋ฉด ๋˜๋Š” ๊ฒƒ์ด์—์š”.

ํ•˜์ง€๋งŒ, ์ด๋ฏธ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์ƒ์„ฑ์ด ๋๋‚œ ๋’ค์— ๋™์ ์œผ๋กœ State ๊ฐ’์„ ๋ฐ”๊พธ๊ณ ์ž ํ•  ๋•Œ๋Š” ์œ„์™€ ๊ฐ™์ด ํ•˜๋ฉด ์•ˆ๋œ๋‹ต๋‹ˆ๋‹ค!


๊ทธ๊ฒƒ์ด ๋ฐ”๋กœ [this.state.mode = 'welcome']๊ณผ ๊ฐ™์ด ํ•˜๋Š” ๊ฒƒ์ด์—์š”.
์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์•ˆ๋˜๋Š” ๊ฒƒ์ด์—์š”.

์ด๋Ÿด ๋•Œ this.setState()์— Body๋ถ€์— ๋‚ด๊ฐ€ ์„ค์ •ํ•˜๊ณ ์ž ํ•˜๋Š” ๋‚ด์šฉ์„ ๊ฐ์ฒด ํ˜•ํƒœ๋กœ ์ค˜์•ผ ํ•œ๋‹ต๋‹ˆ๋‹ค!

๊ทธ ์ด์œ ๋Š” ๋ฌด์—‡์ผ๊นŒ? ๋ฆฌ์—‘ํŠธ ์ž…์žฅ์—์„œ๋Š” [this.state.mode = 'welcome']์ฒ˜๋Ÿผ ๋ฐ”๊ฟ”๋ฒ„๋ฆฌ๋ฉด ๋ฆฌ์—‘ํŠธ ๋ชจ๋ฅด๊ฒŒ ๋ชฐ๋ž˜ ๋ฐ”๊พผ๊ฒƒ๊ณผ ๊ฐ™์€ ๊ฒƒ์ด์—์š”.
๊ทธ๋ž˜์„œ ๋ชจ๋ฅด๋Š” ๊ฑฐ๋‹Œ๊นŒ ๋žœ๋”๋ง์„ ํ•  ์ˆ˜ ์—†๋Š” ๊ฒƒ์ด์—์š”.

๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— State ๊ฐ’์ด ๋ฐ”๋€Œ๋ฉด setState๋ฅผ ์จ์•ผํ•œ๋‹ต๋‹ˆ๋‹ค!

 

 


 

์ฃผ๋‹ˆํ•˜๋ž‘์˜ ๊ธ€์ด ๋งˆ์Œ์— ๋“œ์…จ๋‚˜์š”? ๊ตฌ๋…๊ณผ ๊ณต๊ฐ! ๊ทธ๋ฆฌ๊ณ , ๋Œ“๊ธ€ ๊ทธ๋ฆฌ๊ณ  ๋ฐฉ๋ช…๋ก์€ ์ฃผ๋‹ˆํ•˜๋ž‘์—๊ฒŒ ๋งŽ์€ ํž˜์ด ๋ฉ๋‹ˆ๋‹ค.

 

728x90
๋ฐ˜์‘ํ˜•