이벤트에 따라 다른 것을 랜더링
마우스를 버튼 위에 올렸을 때
색깔이 변하는 효과를 주는 경우들 .. ?
conditional rendering
inline styling
mouse events
managing state
버튼 기본 세팅
index.js에서 기본 세팅한 후
App.js에서 버튼 만들기
CSS
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-weight: 300;
}
body {
font-family: "Source Sans Pro", sans-serif;
color: white;
font-weight: 300;
background: #50a3a2;
width: 100%;
height: 100%;
}
.container {
margin: 10% auto;
padding: 80px 0;
text-align: center;
}
.container h1 {
font-size: 40px;
font-weight: 200;
}
input {
border: 1px solid rgba(252, 252, 252, 0.4);
background-color: rgba(252, 252, 252, 0.2);
width: 250px;
border-radius: 3px;
font-family: "Source Sans Pro", sans-serif;
padding: 10px 15px;
margin: 0 auto 10px auto;
display: block;
text-align: center;
font-size: 18px;
color: white;
font-weight: 300;
}
button {
appearance: none;
outline: 0;
background-color: white;
border: 0;
padding: 10px 15px;
color: #50a3a2;
border-radius: 3px;
width: 250px;
font-size: 18px;
}
html attribute 이용해서 이벤트 핸들링
버튼을 눌렀을 때 콘솔에서 clicked가 뜨도록 한다.
버튼을 눌렀을 때 <h1> 텍스트 Hello를 Submitted로 변경해 보자.
1 useState 불러오기
2 useState hook 사용해서 h1도 세팅하고 함수도 설정하기
3 마우스 클릭시 useState 안 함수 부르기
4 h1을 오브젝트로 변경하기
버튼 위에 마우스 올려놨을 때 색깔 변하게 하기
HTML Event Attributes를 보면 mouse event 중에
mouse-over, mouse-out을 사용해서 작업을 해보자.
https://www.w3schools.com/tags/ref_eventattributes.asp
마우스를 올려 놨을 때 버튼이 검은 색으로 변하게 해보자
1 useState hook 만들기
2 함수 만들기
3 isMouseOver가 true인지 false인지에 따라 색 변하게 하기
4 함수 부르기
마우스를 올리면 색이 변하게 되었다.
하지만 마우스를 치워도 색은 그대로 검은 색이다.
마우스를 치웠을 때는 버튼 색이 흰색이 되도록 해보자 .
onMouseOut 함수를 만들어
버튼 클릭시 호출하고
함수 안에서는 setMouseOver가 false로 바뀌어서 색을 바뀌게 한다.
import React, { useState } from "react";
function App() {
const [headingText, setHeadingText] = useState("Hello");
const [isMouseOver, setMouseOver] = useState(false);
function handleClick() {
setHeadingText("Submitted");
}
function handleMouseOver(){
setMouseOver(true);
}
function handleMouseOut(){
setMouseOver(false);
}
return (
<div className="container">
<h1>{headingText}</h1>
<input type="text" placeholder="What's your name?" />
<button
style = {{backgroundColor: isMouseOver? "black": "white"}}
onClick={handleClick}
onMouseOver={handleMouseOver}
onMouseOut={handleMouseOut}>Submit
</button>
</div>
);
}
export default App;