React - Handling Events

River·2023년 5월 22일
0

React

목록 보기
5/10

이벤트 거는 방법

  • 상황에 맞게 활용할 것

1. 미리 함수를 만든 후 전달

import World from "./World";
import styles from "./Hello.module.css";

export default function Hello(){

    function showName() {
        console.log("Han");
    }
return (
    <div>
    <h1>Hello</h1>
    <button onClick={showName}>Show name</button>
    >
        Show age
        </button>
    </div>
    );
}  

2. onClick 내부에 직접 함수 작성

import World from "./World";
import styles from "./Hello.module.css";

export default function Hello(){

return (
    <div>
    <h1>Hello</h1>
    <button onClick={() => { 
            console.log(50);
        }}
    >
        Show age
        </button>
    </div>
    );
}  

import World from "./World";
import styles from "./Hello.module.css";

export default function Hello(){

    function showName() {
        console.log("Han");
    }
    function showAge(age) {
        console.log(age);
    } 
    function showText(e) { //event 
        console.log(e.target.value); 
        // value 값을 인풋 줬을 때 작성한 값 
        // target 값은 <input type="text" onChange={showText}/> 
    }

    return (
    <div>
        <h1
        style={{
            color: "#f00",
            borderRight: "12px solid #000",
            marginBottom: "50px",
            opacity: 0.5,
        }}
        >
            Hello
        </h1>
        <div className={styles.box}>Hello</div> 
        <button onClick={showName}>Show name</button>
        <button onClick={() => { /
            console.log(50);
        }}
        >
        Show age
        </button>
        <input type="text" onChange={showText}/>  // target 
    </div>
    );
}   
profile
Passionate about My Dreams

0개의 댓글