TIL 9일차

KHW·2021년 8월 17일
0

TIL

목록 보기
8/39

명령형 / 선언형

주제명령형선언형
구현방법어떻게 가공 / 어떻게 구현무엇을 나타내야 하냐
예시for if while문 => 처음배울때 대부분map reduce filter / HTML
  • 명령형 : 어떤 값을 어떻게 돌려서 처리한다

  • 선언형 : HTML을 따르고 화면 그리는 코드를 따로 짜진 않아도 알아서 될거야

  • 선언형 : map filter reduce에 의해 ~과정을 진행할거지 과정 내부의 처리는 알아서 할테니 신경쓰지 않을거야


토글버튼 만들기

1. 버튼 생성시 코드 추가 작성


<body id='app'>
<script>
    const $button1 = document.createElement('button');
    $button1.textContent = 'button1';
    const $button2 = document.createElement('button');
    $button2.textContent = 'button2';
    const $button3 = document.createElement('button');
    $button3.textContent = 'button3';

    const toggleButton = ($button) => {
        if($button.style.textDecoration === ''){
            $button.style.textDecoration= 'line-through';
        }
        else{
            $button.style.textDecoration= '';
        }   
    }

    document.querySelector('#app').appendChild($button1);
    document.querySelector('#app').appendChild($button2);
    document.querySelector('#app').appendChild($button3);

    document.querySelectorAll('#app button').forEach($button =>
        $button.addEventListener('click',(e)=>{
            console.log(this, $button, e.target)
            toggleButton(e.target);
        }))


</script>
</body>

단점 : 매번 만들때마다 각각의 button을 만들고 textContent 코드를 추가하고 appendChild를 추가해야한다. => 그나마 addEventListener도 querySelectorAll 이용해서 줄인거지만


2. 버튼 추가시 new 만 추가


<body id='app'>
<script>
    function ToggleButton({
        $target,
        text
    }){
        const $button = document.createElement('button');
        let isInit = false
        
        this.render = ()=>{
            $button.textContent = text   
            if( !isInit){
            $target.appendChild($button)

            $button.addEventListener('click',()=>{
                if($button.style.textDecoration === 'line-through')
                    $button.style.textDecoration = ''
                else
                    $button.style.textDecoration = 'line-through'
            })
            isInit = true;
            }

        }
        this.render();
    }

    const $app = document.querySelector('#app');

    const btn1 = new ToggleButton({
        $target:$app,
        text:'Button1'
    })

    new ToggleButton({
        $target : $app,
        text : 'Button2'
    })

    new ToggleButton({
        $target : $app,
        text : 'Button3'
    })
</script>
</body>

장점 : 생성자 함수에 필요한 내용을 전부 넣어 객체를 만들 시 new ToggleButton({대상})을 통해 필요한 내용을 만들어 진행하여 코드의 재사용성이 높다.


상태와 재사용성

1. this.state

this.state = {
            clickCount : 0,
            toggled:false
        }

필요한 조건에 해당하는 key와 value를 설정할 수 있다.

2. this.setState

        this.setState = (nextState) => {
            this.state = nextState
            this.render()
        }

this.render를 포함하고 nextState를 통해 상태를 변화시킨다.

3. this.render

this.render = ()=>{
            dom.textContent = text;
            dom.style.textDecoration = 
            this.state.toggled ?'line-through' : 'none'
        }

this.state의 내부 상태에 따라 Dom과 관련 코드를 수정하는 역할을 담당


전체코드 풀이


<body id='app'>
<script>
    function ToggleTag({
        $target,
        text,
        tag,
        onClick
    }){

        this.state = {
            clickCount : 0,
            toggled:false
        }

        this.setState = (nextState) => {
            this.state = nextState
            this.render()
        }

        this.render = ()=>{
            dom.textContent = text;
            dom.style.textDecoration = 
            this.state.toggled ?'line-through' : 'none'
        }

        const dom = document.createElement(tag);
        $target.appendChild(dom);

        setTimeout(()=>{
            this.setState({
                clickCount : this.state.clickCount + 1,
                toggled  : !this.state.toggled
            })
        },3000)

        this.render();
    }

    const $app = document.querySelector('#app');

    new ToggleTag({
        $target:$app,
        text:'Button1',
        tag : 'button',
        onClick: (clickCount)=>{
            if(clickCount % 3=== 0){
                alert('3번째 클릭')
            }
        }
    })

    new ToggleTag({
        $target : $app,
        text : 'div',
        tag : 'div',
        onClick: (clickCount)=>{
            if(clickCount % 2=== 0){
                alert('3번째 클릭')
            }
        }
    })

    new ToggleTag({
        $target : $app,
        text : 'ul',
        tag : 'ul'
    })
    
</script>
</body>

$app을 기준으로 자식태그에 tag에 해당하는 태그를 생성하고 text값을 집어넣는다.

setTimeout에 의해 3초뒤에 this.setState가 발생하고 해당하는 this.state의 변경 후 this.render가 실행되어
this.state.toggled ?'line-through' : 'none' 의 결과로
line-through가 되어 3초뒤에는 text에 모두 중간 작대기가 붙는다.


느낀점

선언형 명령형 프로그래밍을 제대로 이해하고 있던것을 한번더 확인 할 수 있었고 가장 기억에 남는 상태변화를 다루는 this.state 부분을 배움으로써 React에 한발 더 다가갈 수 있었다.

profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

1개의 댓글