본문 바로가기
React를 같이 배워보자

React 3일차-Event Handling

by 멈추지않아 2022. 1. 22.

오늘은 이벤트핸들링 에 대해서 해보자  오늘은 주말이라 거진 저녁 8시부터 공부를 시작해서 양이 얼마 안된다.... 

자 평소처럼 npx serve로 localhost 열고 script에 이거 넣어주자

//함수로 구현
    // function Component(){
    //     return(
    //         <div>
    //             <button onClick={()=>{console.log("clicked")}}>클릭</button>

    //         </div>
    //     );
    // }
    //클래스로 구현
    class Component extends React.Component{
        state={
            count:0,
        }
        // render내부에서 함수정의
        // render(){
        //     return(  
        //     <div>
        //         <p>{this.state.count}</p>
        //         <button onClick={()=>{
        //             console.log("clicked")
        //             this.setState((pre) => ({...pre,count:pre.count+1}))
               
        //         }}>클릭</button>
               
        //     </div>
        // );

       
       // }
       //render 외부에서 함수정의
       //에로우function안쓸때 쓰는거
    // constructor(props){
    //     super(props);
    //     this.click=this.click.bind(this)

    // }
        render(){
            return(  
            <div>
                <p>{this.state.count}</p>
                <button onClick={this.click}>클릭</button>
               
            </div>
        );
    }
    click=()=>{
        console.log("clicked")
        this.setState((pre) => ({...pre,count:pre.count+1}))
    }
}
    ReactDOM.render(<Component/>,document.querySelector("#root"))

요롷게 나올거다

이런화며이 나오면 된거다

우선 함수로 구현하는거부터 해보자 

function Component(){
        return(
            <div>
                <button onClick={()=>{console.log("clicked")}}>클릭</button>

            </div>
        );
    }
ReactDOM.render(<Component/>,document.querySelector("#root"))
이렇게 한세트다 우선 여기서 대부분 다 설명했던거고 
<button onClick={()=>{console.log("clicked")}}>클릭</button>
요거 중에 

onClick={()=>{console.log("clicked")}

 이부분만 설명하겠다 우선 기본구조부터 보면이벤트이름={(전달할변수)=>{함수내용}}이다이벤트이름은 카멜케이스로 작성된다.https://zetawiki.com/wiki/%EC%B9%B4%EB%A9%9C%ED%91%9C%EA%B8%B0%EB%B2%95_camelCase,_%ED%8C%8C%EC%8A%A4%EC%B9%BC%ED%91%9C%EA%B8%B0%EB%B2%95_PascalCase

 

카멜표기법 camelCase, 파스칼표기법 PascalCase - 제타위키

다음 문자열 포함...

zetawiki.com

여기가면 카멜 케이스가 뭔지 나와있다 카멜표기법이랑 같은 말이다

전달할 변수  함수내용 이부분은 앞에 한번설명해서 넘어가겠다

그럼 onClick이건 뭐냐 클릭 할때 마다 함수를 실행하겠다 라는 말이다

<button onClick={()=>{console.log("clicked")}}>클릭</button>

이거는 클릭이라는 글자가있는 버튼을 클릭할때마다 콘솔에 clicked라고 쓰겠다 라는 의미이다.

ReactDOM을 활용해 만든 버튼을 클릭할때마다 콘솔에 clicked라고 쓰겠다 라는것이다.

이벤트는 클릭만있는것이아니고 여러가지 많다

https://jenny-daru.tistory.com/17여기 이벤트 종류가 적혀있다

 

JavaScript - 이벤트(Event), 이벤트의 종류, 이벤트 연결

이벤트 웹페이지에서 마우스를 클릭했을 때, 키를 입력했을 때, 특정요소에 포커스가 이동되었을 때 어떤 사건을 발생시키는 것 이벤트의 종류  1) 마우스 이벤트 이벤트 설명 click 요소에 마우

jenny-daru.tistory.com

   이제 클래스로 한번 정의 해보자
class Component extends React.Component{
        state={
            count:0,
        }
        //render내부에서 함수정의
        render(){
            return(  
            <div>
                <p>{this.state.count}</p>
                <button onClick={()=>{
                    console.log("clicked")
                    this.setState((pre) => ({...pre,count:pre.count+1}))
               
                }}>클릭</button>
               
            </div>
        );

       
       }
       render 외부에서 함수정의
       에로우function안쓸때 쓰는거
    constructor(props){
        super(props);
        this.click=this.click.bind(this)

    }
        render(){
            return(  
            <div>
                <p>{this.state.count}</p>
                <button onClick={this.click}>클릭</button>
               
            </div>
        );
    }
    click=()=>{
        console.log("clicked")
        this.setState((pre) => ({...pre,count:pre.count+1}))
    }
}
    ReactDOM.render(<Component/>,document.querySelector("#root"))
한세트씩 분리해서 보겠다 우선 render내부에서 해결하는것이다.

 

class Component extends React.Component{
        render(){
            return(  
            <div>
                <p>{this.state.count}</p>
                <button onClick={()=>{
                    console.log("clicked")
                }}>클릭</button>
               
            </div>
        );
       }

 }

보듯이 함수에서 정의한것이랑 크게 다른것은 없다.

class Component extends React.Component{

 render(){
            return(  
            <div>
                <button onClick={this.click}>클릭</button>
               
            </div>
        );
    }
    click(){
        console.log("clicked")
        
    }
}
    ReactDOM.render(<Component/>,document.querySelector("#root"))
 일반 함수처럼 class 내부에 원하는이름으로 함수를 정의하고 

<button onClick={this.click}>클릭</button>여기서 this.click을 this.원하는 함수이름으로 바꺼주면 적용된다. 

this는 여기 내부에 있는 것을 쓰겠다는 의미이다.  그럼이제 원문 처럼 count라는 데이터를 넣어서 실행해보자

 

우선 render내부에서 함수 정의 할때

class Component extends React.Component{
        state={
            count:0,
        }
        //render내부에서 함수정의
        render(){
            return(  
            <div>
                <p>{this.state.count}</p>
                <button onClick={()=>{
                    console.log("clicked")
                    this.setState((pre) => ({...pre,count:pre.count+1}))
               
                }}>클릭</button>
               
            </div>
        );
기서 다른건 다 봤읜 이해가 될거고 요부분이  

this.setState((pre) => ({...pre,count:pre.count+1}))

이해가 안될것이다

setState 이건 state내용을 바꿀수있는 특별한 함수 이름이다 저이름을쓰면 함수 내부에서 state 내용을 바꿀수있다. 

이렇게 몇가지 특별한 기능을하는 함수이름이 있다.

(pre)이건 전달되는 데이터를 받아줄 변수이다 pre를 자기가 원하는 다른걸로 바꺼도된다.

즉 여기서는 state 내용이 pre에 저장이된다.

...pre,count:pre.count+1이거는 조금 복잡할수 있다. 우선 ...pre는 pre 내용을 다 가져오겠고 그뒤에 뭘 더추가할때 쓰는거다 보통 일반적으로 pre그대로 넣지 못할때 쓴다 데이터타입이 다를때 자주쓴다.

count:pre.count+이거는 저번에 설명했듯이 count라는 이름으로 pre에 있는count라는 값에 1을 더한다는 뜻이된다.

...pre,count:pre.count+1이거는 pre의 내용에 pre.count+1이거를 넣겠다는 것이다 새로운것이면 추가가될것이고 기존에 있으면 덮어써질것이다.

그래서 결국은 클릭할때마다 count값이 1씩 증가한다.

 

이제 render외부에서 함수 정의할당시 state값을 변경하는 것을 알아보자 우선 두가지 방법이 있다.

1.그냥 function활용

class Component extends React.Component{
    state={
            count:0,
        }

    constructor(props){
        super(props);
        this.click=this.click.bind(this);
    }
        render(){
            return(  
            <div>
                <p>{this.state.count}</p>
                <button onClick={this.click}>클릭</button>
            </div>
        );
    }
    click(){
        console.log("clicked")
        this.setState((pre) => ({...pre,count:pre.count+1}))
    }
}

ReactDOM.render(<Component/>,document.querySelector("#root"))
여기서는 다 이해가 될거고 
  constructor(props){
        super(props);
        this.click=this.click.bind(this);
    }
이부분 중 this.click=this.click.bind(this);이건 왜 쓰는지 이해가 안될것이다 
우선 저걸써야되는 이유는 click이라 정의한 함수에서 this가 있다 저기서 this는 class 내부를 뜻하는게 아니고 click이라는 함수의 내부를뜻한다. 그래서 click함수내부에서 setState를 찾기때무에 오류가  나온다.
그래서 그설 해주는것이 생성자를 활용해서 this.click=this.click.bind(this);이걸 추가해주면 클래스 내부를 뜻하게 도시해결된다. 이거는 생각보다 귀찮아서 많이쓰지 않느다. 보통 2번 에로우function을 활용한것을 쓴다.

2.에로우 function활용

class Component extends React.Component{
    state={
            count:0,
        }
        render(){
            return(  
            <div>
                <p>{this.state.count}</p>
                <button onClick={this.click}>클릭</button>
            </div>
        );
    }
    click=()=>{
        console.log("clicked")
        this.setState((pre) => ({...pre,count:pre.count+1}))
    }
}

ReactDOM.render(<Component/>,document.querySelector("#root"))

이거는 생성자 만들 필요 없이 함수이름(){함수내용} 이런 형식이였던것을 함수이름=()=>{함수내용} 이렇게 바꺼주면

생성자를 적을필요없이 this가 클래스 내부를 가르키게 된다. 정말편하고 쉽다.

저기 괄호에는 원래 데이터를 저장해줄 변수가 필요한데 전달받을 데이터가 없어서 빈칸이다.

 

오늘은 주말이니까 이까지 하겠다ㅎㅎㅎ 뭐 다른공부하다 삘받으면 다시 돌아올수도 있다 ㅋㅋㅋㅋ