React JS #6 이벤트 처리(Handling Events) - 초보자를 위한 리액트 강좌

Robyn·2023년 4월 2일
0

이벤트 처리하는 방법

showAge(age) age라는 매개변수 전달

export default function Hello() {
    function showName() {
        console.log('Robyn');
    }

    function showAge(age) {
        console.log(age);
    }
    
    function showText(e){
        console.log(e.target.value)
    }

    return (
        <div>
            <h1>Hello</h1>
            <button onClick={showName}>Show name</button>
            <button onClick={() => {
                showAge(29);
            }}>Show age</button>
            <input type='text' onChange={(showText)}></input>
        </div>
    );
}

위의 onChange에서는 showText라는 함수가 들어간다.

대신 이렇게 쓸 수도 있다.

export default function Hello() {
    function showName() {
        console.log('Robyn');
    }

    function showAge(age) {
        console.log(age);
    }

    return (
        <div>
            <h1>Hello</h1>
            <button onClick={showName}>Show name</button>
            <button onClick={() => {
                showAge(29);
            }}>Show age</button>
            <input type='text' onChange={(e) => {
                console.log(e.target.value)
            }}></input>
        </div>
    );
}

함수를 바로 작성해버리는 것이다.

또 이렇게 쓸 수도 있다.

export default function Hello() {
    function showName() {
        console.log('Robyn');
    }

    function showAge(age) {
        console.log(age);
    }
    
    function showText(txt){
        console.log(txt)
    }

    return (
        <div>
            <h1>Hello</h1>
            <button onClick={showName}>Show name</button>
            <button onClick={() => {
                showAge(29);
            }}>Show age</button>
            <input type='text' onChange={e => {
                const txt = e.target.value;
                showText(txt);
            }}></input>
        </div>
    );
}

전달해주는 것이다.

0개의 댓글