Language/React.js

[React] Props와 EventHandling 기초

JJcoding 2024. 10. 16. 14:41

Props로 데이터 전달하기

App.jsx

import './App.css'
import Button from './components/Button';

function App() {

  return (
    <>
      <Button text={"메일"} color={"red"} />
      <Button text={"카페"}/>
      <Button text={"블로그"}/>
    </>
  )
}

export default App;
  • 부모 컴포넌트에서 Props를 보낸다.

Button.jsx

const Button = ({props}) => {
    console.log(props);
    return (
        <button style={{color : props.color}}>
            {props.text} - {props.color.toUpperCase()}
        </button>
    );
};

Button.defaultProps = {
    color:"black",
};

export default Button;
  • 객체 형태로 받아온 props를 꺼내서 점 표기법으로 사용한다.
const Button = ({text, color}) => {
    return (
        <button style={{color : color}}>
            {text} - {color.toUpperCase()}
        </button>
    );
};

Button.defaultProps = {
    color:"black",
};

export default Button;
  • 구조 분해 할당을 활용하여 값을 그대로 받아올 수도 있다.

App.jsx

import "./App.css";
import Button from "./components/Button";
import Header from "./components/Header";

function App() {
  const buttonProps = {
    text: "메일",
    color: "red",
    a: 1,
    b: 2,
    c: 3,
  };

  return (
    <>
      <Button {...buttonProps} />
      <Button text={"카페"} />
      <Button text={"블로그"}>
	      <div>자식요소</div>
        <Header />
      </Button>
    </>
  );
}

export default App;
  • 부모 컴포넌트에서 전달할 props가 많을 경우 객체로 만들어 스프레드 연산자로 보낼 수도 있다.
  • html 태그나 컴포넌트도 props로 보낼수 있다.

Button.jsx

const Button = ({ text, color, children }) => {
  return (
    <button style={{ color: color }}>
      {text} - {color.toUpperCase()}
      {children}
    </button>
  );
};

Button.defaultProps = {
  color: "black",
};

export default Button;
  • children 이라는 요소로 자식 요소를 받을 수 있다.
  • props는 부모에서 자식으로만 보낼 수 있다.

Event Handling

  • Event 란? 웹 내부에서 발생하는 사용자의 행동을 말한다. ex) 버튼 클릭, 메세지 입력, 스크롤 등
  • 이벤트 핸들링이란 이벤트가 발생했을 때 그것을 처리하는 것을 말한다. ex ) 버튼 클릭 시 경고창 노출 등

Button.jsx

const Button = ({ text, color, children }) => {
 // 이벤트 객체
  const onClickButton = (e) => {
    console.log(e);
    console.log(text);
  };

  return (
    <button onClick={onClickButton} style={{ color: color }}>
      {text}
      {children}
    </button>
  );
};

Button.defaultProps = {
  color: "black",
};

export default Button;
  • onClick 과 같은 함수를 ‘이벤트 핸들러’ 라고 부른다.
  • 여기서 주의할 점은 onClick={onClickButton} 과 같이 소괄호( )를 넣지 않아야 한다는 점이다. 함수의 결과를 호출하는 것이 아닌 함수 자체를 호출하는 것이라고 생각하면 쉽다.
  • 여기서 e 매개변수는 SyntheticBaseEvent 를 나타내는데 이것을 ‘합성 이벤트 객체’ 라고 한다.
  • 합성 이벤트 객체란 ?
    • 모든 웹 브라우저의 이벤트 객체를 하나로 통일한 형태를 말한다.
    • Cross Browsing Issue (브라우저 별 스펙이 달라 생기는 문제)를 해결할 수 있다.
    • 하나의 통일된 규격으로 이벤트 객체를 포맷팅 해준다.

 

출처 : 한입 크기로 잘라먹는 리액트