본문 바로가기
💻CODING/react. vue

[react] 리액트로 구구단 게임 만들기(ft. hooks 방식, cdn 설치)

by 코딩하는 갓디노 2021. 3. 14.

구구단 게임

 

리액트 hooks로 구현한
구구단 게임 입니다.

 

예제는 인프런의 제로초, "조현영"님의 강의를 들으면서 공부한 내용입니다.

 

Class 방식과 Hooks 방식의 비교

Class 방식과 Hooks 방식의 비교
· Class보다는 Hooks를 리액트에서 권장하고 있는 방식입니다. 
· Class보다 Hooks가 코드가 훨씬 간결합니다.
· 모든 state를 쪼개서 선언합니다.
· this.state, this.setState을 사용 안합니다. 
· ref를 React.useRef으로 문법을 사용합니다.
· render() 함수 부분은 같습니다.
· Class에서는 state가 변경될 때마다 render함수 내에서만 재실행되지만,
Hooks에서 함수 전체가 재실행되기 때문에 속도가 더 느릴 수 있습니다.

 

state 사용 방법 비교

클래스

this.state = {
  first: Math.ceil(Math.random() * 9),
  second: Math.ceil(Math.random() * 9),
  value: '',
  result: '',
};

 

Hooks

const [first, setFirst] = React.useState(Math.ceil(Math.random() * 9));
const [second, setSecond] = React.useState(Math.ceil(Math.random() * 9));
const [value, setValue] = React.useState('');
const [result, setResult] = React.useState('');
const inputRef = React.useRef(null);     

 

리액트, 바벨 cdn 설치

간단한 예제는 cdn을 이용하여, react와 babel을 설치합니다.

<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> 
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> 
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

 

리액트 구구단 게임

html

<div id="root"></div>

 

script

   <script type="text/babel">
        const Gugudan = () => {
            const [first, setFirst] = React.useState(Math.ceil(Math.random() * 9));
            const [second, setSecond] = React.useState(Math.ceil(Math.random() * 9));
            const [value, setValue] = React.useState('');
            const [result, setResult] = React.useState('');
            const inputRef = React.useRef(null);     
            
            const onSubmitForm = (e) => {
                e.preventDefault();
                if(parseInt(value) === first * second) {
                    setResult(value + ' 정답입니다.');
                    setFirst(Math.ceil(Math.random()* 9));
                    setSecond(Math.ceil(Math.random() * 9));
                    setValue('');
                    inputRef.current.focus();
                }else{
                    setResult(value + ' 틀렸습니다.');
                    setValue('');
                    inputRef.current.focus();
                }
            };
            
            const onChangeInput = (e) => {
                setValue(e.target.value);
            }        
                    
            return (
                <React.Fragment>
                     <div>{first} 곱하기 {second}는?</div>
                     <form onSubmit={onSubmitForm}>
                         <input ref={inputRef} value={value} onChange={onChangeInput} />
                         <button type="submit">입력</button>
                     </form>
                     <div id="result">{result}</div>   
                </React.Fragment>
            )        
        }
    </script>
    <script type="text/babel">
        ReactDOM.render(<Gugudan />, document.querySelector('#root'));
    </script>

 

화면 결과 (Result 보기)


class 방식으로 구구단 게임 구현은 아래로 이동해 주세요. 

https://goddino.tistory.com/141

 

[js] 리액트로 구구단 게임 만들기(ft. 클래스 방식, cdn으로 설치)

리액트 클래스로 구현한 구구단 게임 입니다. 예제는 인프런의 제로초, "조현영"님의 강의를 들으면서 공부한 내용입니다. Points · state: 변하는 데이터는 state(변경 전 데이터)로 넣는다. · input의

goddino.tistory.com

반응형

댓글