티스토리 뷰

 

 

class로 작성 시

// WordRelay.jsx

const React = require('react');
const { Component } = React;

class WordRelay extends Component {
  state = {
    word: '리엑트', // 끝말잇기 첫 단어
    value: '', // 사용자 입력 값
    result: '', // 정답/오답 텍스트
  }

  onSubmitForm = (e) => {
    e.preventDefault(); // submit 기본 이벤트 방지
    if( this.state.word[this.state.word.length -1] === this.state.value[0] ) {
    // word의 마지막 글자와 value의 첫글자가 같다면
      this.setState((prevState) => {
        return {
          word: prevState.value, // value 값을 word에 저장
          value: '',
          result: '정답'
        }
      });
      this.input.focus();
    } else {
      this.setState({
        value: '',
        result: '오답'
      })
    }
  }

  onChangeInput = (e) => { // 사용자가 input 입력 시 state에 입력 값 저장(input value => state value)
    this.setState({value: e.target.value});
  }

  input; // input 변수 선언
  onRefInput = (el) => { 
    this.input = el; // input 변수에 input dom 저장
  }

  render() {
    return (
      <>
        <p>{this.state.word}</p>
        <form onSubmit={this.onSubmitForm}>
          <input type="text" ref={this.onRefInput} value={this.state.value} onChange={this.onChangeInput} />
          {/* value={this.state.value} => state에서 변경된 값을 input value로 가져오기(state value => input value) */}
          <button type='submit'>입력!</button>
        </form>
        <p>{this.state.result}</p>
      </>
    )
  }
}

module.exports = WordRelay;

 

 

 

함수형 컴포넌트로 작성 시

// WordRelay.jsx

const React = require('react');
const { useState, useRef } = React;

const WordRelay = () => {
  // state
  const [word, setWord] = useState('리엑트'); // 끝말잇기 첫 단어
  const [value, setValue] = useState(''); // 사용자 입력 값
  const [result, setResult] = useState(''); // 정답/오답 텍스트
  const inputRef = useRef(); // input을 지정하기 위해 선언

  const onSubmitForm = (e) => {
    e.preventDefault();
    if( word[word.length -1] === value[0] ) { // word의 마지막 글자와 value의 첫글자가 같다면
      setWord(value);
      setValue('');
      setResult('정답');
      inputRef.current.focus();
    } else {
      setValue('');
      setResult('오답');
      inputRef.current.focus();
    }
  }

  const onChangeInput = (e) => {
    setValue(e.target.value);
  }

  return (
    <>
      <p>{word}</p>
      <form onSubmit={onSubmitForm}>
        <input type="text" ref={inputRef} value={value} onChange={onChangeInput} />
        <button type='submit'>입력!</button>
      </form>
      <p>{result}</p>
    </>
  )

}

module.exports = WordRelay;

 

 

반응형
댓글
반응형
최근에 올라온 글
공지사항