개발자로 전향중

React Hook: useEffect(), EventListener 본문

React

React Hook: useEffect(), EventListener

hovinee 2022. 1. 22. 12:13
더보기

<aside> ⚠️ 이벤트 리스너는 사용자가 어떤 행동(=이벤트)을 하는 지 아닌 지 지켜보다가 알려주는 것입니다. 대표적으로는 마우스 클릭, 터치, 마우스 오버, 키보드 누름 등이 자주 쓰여요! 

</aside>

<aside> 🔥 이벤트 리스너는 <div onClick={}>에서처럼 엘리먼트에 직접 넣어줄 수도 있지만, 이번 강의에서는 addEventListener를 통해 추가해볼거예요.

눈으로만 보고 어떻게 쓰는구나 감만 잡아봅시다. 😉

</aside>

App.js

import React from "react";
import Text from "./Text";

---------->
class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {};
    this.circle = React.createRef(null);
  }


  hoverEvent = (e) => {
    console.log(e.target);
    console.log(this.circle.current)
    this.circle.current.style.background = "yellow"
  }

  componentDidMount() {
    console.log(this.circle);
    this.circle.current.addEventListener("mouseover", this.hoverEvent)
    //마우스를 mouseover하면 hoverEvent를 실행시켜2줘!
  }

  componentWillUnmount() {
    this.circle.current.removerEventListener("mouseover", this.hoverEvent)
  }
----------> class component 동그라미 부분에 이벤트처리
  render() {
    return (
      <div style={{ width: "100vw", height: "100vh", textAlign: "center" }}>
        <Text />
        <div style={{ margin: "auto", width: "250px", height: "250px", 
        background: "green", borderRadius: "250px" }} ref={this.circle}></div>

      </div>
    );
  }
}

export default App;
더보기

<aside> 👉 이벤트 리스너는 어디에 위치해야할까요? 클릭을 하건, 마우스를 올리건 DOM 요소가 있어야 이벤트가 발생하는 지 지켜볼 수 있겠죠? → 그럼 함수형 컴포넌트에서는 componentDidMount() 역할을 하는 친구를 가져다 써야겠네요! useEffect() 훅을 써봅시다!

</aside>

 

<aside> 📃 useEffect()는 리액트 훅이에요. 라이프 사이클 함수 중 componentDidMount와 componentDidUpdate, componentWillUnmount를 합쳐둔 거라고 생각하면 금방 이해할 수 있어요!

</aside>

Text.js: 함수형 컴포넌트 글자 배경에 이벤트 처리

import React from "react";

const Text = (props) => {
const text = React.useRef(null);

const hoverEvent = () => {
    text.current.style.background = "yellow"
}

React.useEffect(() => {
    text.current.addEventListener("mouseover", hoverEvent);
    //컴포넌트 등록

    return () => {
        text.current.removeEventListener("mouseover", hoverEvent);
    //컴포넌트 해제
    }
}, []);
return (
<h1 ref={text}>텍스트입니다!</h1>
)
}

export default Text;

'React' 카테고리의 다른 글

리액트에서 자주쓰는 if문 작성패턴 5개  (0) 2022.01.22
react(리액트) JSX 배열 반복문 렌더링 - for/map/forEach  (0) 2022.01.22
React router dom v6  (0) 2022.01.22
React Hook: useref()  (0) 2022.01.22
React Hook: useState(함수)  (0) 2022.01.22