웹/React

[React]_구구단

Ellie67 2021. 2. 28. 22:15

 

 

 


1부터 9까지 랜덤으로 두 수가 선택된다.

답을 입력하고, 정답이면 정답과 답이 출력되고 오답이면 땡이 출력된다.

 


 

<html>
    <head>
        <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    </head>
    <body>
        <div id="root"></div> <!-- 결과: <div id="root"><button>Like</button></div>-->
        <script type="text/babel">
            class GuGUDan extends React.Component{
                constructor(props){
                    super(props);
                    this.state = {
                        first: Math.ceil(Math.random() * 9),
                        second: Math.ceil(Math.random() * 9),
                        value: '',
                        result: '',
                        inputNum: ''
                    };
                }

                onSubmit=(e)=>{
                    e.preventDefault();
                    if(parseInt(this.state.value)===this.state.first * this.state.second){
                    this.setState((preState) => {
                        return {
                            result: '정답 :',
                            first: Math.ceil(Math.random() * 9),
                            second: Math.ceil(Math.random() * 9),
                            value: ' ',
                            inputNum: preState.value
                        };
                    });
                    this.input.focus();
                    } else{
                        this.setState({
                            result: '땡',
                            value: '',
                            inputNum: ''
                        });
                    }
                };

                onChange=(e) => this.setState({value: e.target.value});

                input;

                onRefInput = (c) => {this.input = c;};

                render(){
                    return (
                        <div>
                            <div>{this.state.first} 곱하기 {this.state.second}는?</div>
                            <form onSubmit={this.onSubmit}>
                                <input ref={this.onRefInput} type="number" value={this.state.value} onChange={this.onChange}/>
                                <button>입력</button>
                            </form>
                            <div>{this.state.result} {this.state.inputNum}</div>
                        </div>
                    );
                }
            }
        </script>
        <script type="text/babel">
            ReactDOM.render(<div><GuGUDan/><br/><br/><GuGUDan/></div>, document.querySelector('#root'));
        </script>
    </body>
</html>