728x90
1. App.js
import "./App.css";
import { img01, img02, img03, img04, img05, img06 } from "./img";
import Block from "./Block";
import { useEffect, useState } from "react";
function App() {
const select = {
scissors: {
name: "가위",
img: img03,
},
rock: {
name: "바위",
img: img02,
},
paper: {
name: "보",
img: img01,
},
};
const [userSelect, setUserSelect] = useState(null);
const [comSelect, setComSelect] = useState(null);
const [result, setResult] = useState(null);
function userClick(selectValue) {
setUserSelect(select[selectValue]);
let arr = Object.keys(select);
let comRandom = Math.floor(Math.random() * 3);
setComSelect(select[arr[comRandom]]);
}
useEffect(() => {
if (!userSelect) {
setResult(null);
return;
}
if (userSelect?.name == comSelect?.name) {
setResult(img06);
} else if (
(userSelect?.name == "가위" && comSelect?.name == "보") ||
(userSelect?.name == "바위" && comSelect?.name == "가위") ||
(userSelect?.name == "보" && comSelect?.name == "바위")
) {
setResult(img05);
} else {
setResult(img04);
}
}, [userSelect, comSelect]);
return (
<div>
<div className="App">
<Block data={userSelect} name="user" />
<Block data={comSelect} name="com" />
<Block data={{ img: result }} name="result" />
</div>
<div>
<button
onClick={() => {
userClick("scissors");
}}
>
가위
</button>
<button
onClick={() => {
userClick("rock");
}}
>
바위
</button>
<button
onClick={() => {
userClick("paper");
}}
>
보
</button>
</div>
</div>
);
}
export default App;
2. Block.js
import React from "react";
const Block = (props) => {
let { data, name } = props;
return (
<div className="block">}
<div>{name}</div>
<img src={data && data.img} />
</div>
);
};
export default Block;
728x90
'개발 > React' 카테고리의 다른 글
[React] 게시판 만들기 (0) | 2022.09.26 |
---|---|
[React] 라우터 사용 (0) | 2022.09.20 |
[React] 함수형 useEffect (0) | 2022.09.19 |
[React] 클래스형 컴포넌트 (2) | 2022.09.19 |
[React] 달력 만들어보기 (0) | 2022.09.14 |