TIL.30 React, State 로 login 구현

Haiin·2020년 12월 4일
0

출저

  • 위코드 강의자료
  • MDN


Login page with React.



구현할 기능 (state과 event 연습)

  • id (@ 가 있는지) : onChange
  • pw (4자리 이상인지) : onChange
  • pw를 보이게
  • input value가 한 글자 이상씩 있으면 버튼 활성화
  • 버튼 클릭했을 때 validation check : onClick


처음 짠 코드


class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      //초기화 상태
      message : "",
      colorId : false,
      colorPw : false,
    }
  }

  goToMain = () => {
    this.props.history.push('/Main');
  }

  handleId  = (e) => {
    if (e.target.value.indexOf('@') === -1) {
      this.setState({
        message : "올바른 이메일 주소를 입력하시라구욥!",
        colorId : false
      })  
    } else {
      this.setState({
        message : "",
        colorId : true
      })    
    }
  } 
  
  handlePw  = (e) => {
    if (e.target.value.length < 6) {
      this.setState({
        message : "6자리 이상 누르시라구욥!",
        colorPw : false
      })
    }
    else {
      this.setState({
        message : "",
        colorPw : true,
      })    
    } 
  }

  render() {
    return (
      <div className="Login">
              <div>Westagram</div>
              <form>
                  <input 
                  className="loginId" 
                  onChange={this.handleId}
                  type="email" 
                  placeholder="이메일 주소"/>
                  <input 
                  className="loginPassword" 
                  onChange={this.handlePw}
                  type="password" 
                  placeholder="비밀번호"/>
                  <p>{this.state.message}</p>
                  <button onClick={this.goToMain} 
                  style={this.state.colorId && this.state.colorPw ? {backgroundColor:"blue"} : {backgroundColor: "yellow"}}>로그인</button>
              </form>
              <div className="forgetQ">비밀번호를 잊으셨나요?</div> 
      </div> 
    )   
  }
}


배운대로 복습

class Login extends React.Component {
  constructor() {
    super();
    this.state = {
      //초기화 상태
      id : "",
      pw : "",
      hiddenPw : true,
    }
  }

  handleValue  = (e) => {
    //구조분해 할당 
    const {id, value} = e.target;
    this.setState({
      [id] : value,   
    })
  } 

  showHide = () => {
    this.setState({
      hiddenPw : !this.state.hiddenPw,
    })
  }

  validationCheck = (e) => {
    e.preventDefault()

    const {id, pw} = this.state;
    if (id.indexOf("@") === -1) {
      alert("올바른 이메일주소가 아닙니다.")
    }
    if (pw.length < 5) {
      alert("4자리 이상 입력하세요.")
    }
    if (id.indexOf("@") !== -1 && pw.length > 4) {
      this.props.history.push('/Main');
    }
  }
  
  render() {

    //console.log(this.state)

    const {id, pw, hiddenPw} = this.state;
    const colorchangeBtn = id.length >= 1 && pw.length >= 1;

    return (
      <div className="Login">
              <div>Westagram</div>
              <form>
                  <input 
                  className="loginId" 
                  id="id"
                  onChange={this.handleValue}
                  type="email" 
                  placeholder="이메일 주소"/>
                  <input 
                  className="loginPassword"
                  id="pw" 
                  onChange={this.handleValue}
                  type={hiddenPw ? "password" : "text"}
                  placeholder="비밀번호"/>
                  <span 
                  onClick={this.showHide}>{hiddenPw ? "Show" : "Hide"}</span>
                  <button 
                  onClick={this.validationCheck}
                  className={colorchangeBtn ? "activate" : ""}>로그인</button>
              </form>
              <div className="forgetQ">비밀번호를 잊으셨나요?</div> 
      </div> 
    )   
  }
}


기억할 것

1. 구조분해 할당.

  • 구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식.
  • 두 개의 input 태그에 각각 id 값(attribute)을 그에 맞는 value값을 가지는 구조분해 할당을 한다.
  • 이는 함수로 만들어지고 onChange 속성에 넣어주면 input에 값이 할당될 때 마다 적용된다.
const {id, value} = e.target; // e.target.id, e.target.value 값으로 비구조할당.
this.setState=({
      [id] : value,  
    })
=> constructor 에 초기화해준 값들을 setState 에 객체로 다시 저장.

2. 함수구별과 jsx 문법.

  • return에서 event명을 써주고 함수를 넣을때 두 가지 모양에 유념하자.

onChange={this.handleId}
onChange={() => this.handleId()}

  • jsx문법으로 작성하고 있기 때문에 js 문법을 사용하고 싶을때는 {}를 써주도록 한다.
  • 위 함수 activateBtn 은 비구조할당이 있었기에 간단하게 함수로(const로 선언)할 수 있었던것.
const checkId = id.includes("a");


0개의 댓글