hmk run dev
클릭하면 색이 바뀌는 Event 본문
더 많은 이벤트리스너를 알고 싶다면
구글링 >> eventlistener mdn 검색
리액트 event는 Ref 먼저 잡아주는 것 필수!
1. App 이라는 div에 ref 먼저 잡아주자
this.div = React.createRef();
2. 그리고 적용
<div className="App" ref={this.div}>
3. 함수만들기
hoverEvent = (e) => {
//이벤트를 e 파라미터로 줘서 그것을 타겟으로 뭔가를 잡아와야함
console.log(e);
console.log(e.target);
e.target.style.background = "#eee"; //e로 타겟을 잡아주고 스타일> 백그라운드 hover효과
};
4. 컴포넌트디드 마운트에서 등록
componentDidMount() {
this.div.current.addEventListener("mouseover", this.hoverEvent);
} // mouseover 마우스 오버 이벤트 등록, this.함수명
5. 컴포넌트 윌 어마운트에서 해제하는 것도 준비
componentWillUnmount() {
this.div.current.removeEventListener("mouseover", this.hoverEvent);
}
import React from "react";
import Nemo from "./Nemo";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.div = React.createRef();
}
hoverEvent = (e) => {
//이벤트를 e 파라미터로 줘서 그것을 타겟으로 뭔가를 잡아와야함
console.log(e);
console.log(e.target);
e.target.style.background = "#eee"; //e로 타겟을 잡아주고 스타일> 백그라운드 hover효과
};
componentDidMount() {
this.div.current.addEventListener("mouseover", this.hoverEvent);
}
componentWillUnmount() {
this.div.current.removeEventListener("mouseover", this.hoverEvent);
}
render() {
return (
<div className="App" ref={this.div}>
<Nemo />
</div>
);
}
}
export default App;
'React' 카테고리의 다른 글
리액트 라우팅 history (0) | 2021.03.23 |
---|---|
리덕스에서 FireStore 사용해보기 (0) | 2021.03.22 |
리액트 인풋 Event 파헤쳐보자! (0) | 2021.03.21 |
state 관리 함수형 컴퍼넌트 (0) | 2021.03.21 |
state 연습 + 코드 상세 해석 (0) | 2021.03.21 |
Comments