react, westagram 기능구현

폴더구성

input 요소를 component화 했다.

InputId.js

import React from 'react';
import { withRouter } from 'react-router-dom';
import './InputId.scss';

class InputId extends React.Component {
  constructor() {
    super();
    this.state = {
      //state 말 그대로 컴포넌트의 상태를 수정.  state는 constructor 안에서만 초기화되며 밖에서는 setState를 사용하여 값을 바꾼다.
      idInputValue: '',
      pwInputValue: '',
    };
  }

  handleIdInput = e => {
    //IdInput은 event의 약자 e를 인자로 받음
    this.setState({
      idInputValue: e.target.value,
    });
  };

  handlePwInput = e => {
    this.setState({
      pwInputValue: e.target.value,
    });
  };

  goToMain = () => {
    this.props.history.push('/Main-HH');
  }; //로그인 버튼 누르면 실행되어 메인으로 들어가도록 하는 함수.

  render() {
    return (
      <section className="inputs">
        <input
          type="text"
          name="ID"
          id="userId"
          placeholder="전화번호, 사용자 이름 또는 이메일"
          onChange={this.handleIdInput}//1.ID input에서 onChange event 발생 --> handleIdInput 함수 실행
        />

        <input
          type="password"
          name="Password"
          id="userPassWord"
          placeholder="비밀번호"
          onChange={this.handlePwInput} //1.ID input에서 onChange event 발생 --> handlePwInput 함수 실행
        />

        <button // 2. 기준에 맞는 경우에만 로그인버튼 색상 활성화.
          type="button"
          className={
            this.state.idInputValue.indexOf('@') !== -1 && //@포함
            this.state.pwInputValue.length >= 5 //비번 5글자 이상
              ? 'Active'
              : 'Disabled'
          }
          disabled={
            this.state.idInputValue.indexOf('@') !== -1 &&
            this.state.pwInputValue.length > 5
              ? false
              : true
          }
          onClick={this.goToMain}
        >
          로그인
        </button>
      </section>
    );
  }
}

export default withRouter(InputId);

Login.js

import React from 'react';
import { withRouter } from 'react-router-dom';
import './Login.scss';
import InputId from './InputId';

class Login extends React.Component {
  render() {
    return (
      <header className="Login">
        <div className="userInfo">
          <div className="westa">westagram</div>
          <InputId /> // 컴포넌트 사용
       	</div>
        <a className="forgotPwd" href="/login-HH">
          비밀번호를 잊으셨나요??
        </a>
      </header>
    );
  }
}

export default withRouter(Login);




Mission 1) Login | 사용자 입력 데이터 저장

  1. ID <input> 에서 onChange event 발생
  2. event 발생 시 handleIdInput 함수 실행
  3. handleIdInput 는 이벤트를 인자로 받음
  4. event가 일어난 요소에 담긴 value 값 (event.target.value)을 state에 저장
  5. 위의 과정을 PW <input> 에도 동일하게 적용

Mission 2) Login | 로그인 버튼 활성화 (validation)

  • 입력한 아이디와 비밀번호가 기준에 맞는 경우에만 로그인 버튼 색상이 활성화될 수 있도록 해주세요.
  • ex. ID - @ 포함 / PW - 5글자 이상
  • 삼항 연산자 적용해서 조건에 따라 버튼 색상에 변화를 주시기 바랍니다.

Mission 3) Main | 댓글 기능

  • 사용자가 댓글 입력 후 enter 를 누르거나 왼쪽의 버튼 클릭 시 댓글이 추가되도록 구현해주세요.
  • 댓글 기능을 구현하기 위해서는 배열 데이터 타입을 활용해야 합니다.
  • Array.map 참고해서 시도해주세요.

Main.js

render 윗부분.

import React from 'react';
import { withRouter } from 'react-router-dom';
import Nav from '../../../components/Nav/Nav';
import './Main.scss';
import Comment from './Comment';

class Main extends React.Component {
  constructor() {
    super();

    this.state = {
      newReply: '',
      replies: [],
    };
  }

  textChange = e => {
    this.setState({
      newReply: e.target.value,
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    if (this.state.newReply.length === 0) return; //값이 없으면 아무일도 없음.
    this.setState({
      replies: this.state.replies.concat(this.state.newReply),

      newReply: '', //newReply state값은 다시 비워준다.
    });
  };

Mission 4) Main | 댓글 컴포넌트화 + props로 데이터 전달

  • map 함수를 활용해 댓글 목록을 구현해주세요.
  • 댓글 하나를 컴포넌트화 시켜주세요.
  • 부모의 state 에 저장된 댓글 데이터에 Array.map() 메소드를 적용해 댓글의 개수만큼 댓글 컴포넌트가 나타나게 해주세요.
  • 필요한 데이터를 props 로 넘겨주세요.
  • 기존에 보였던 대로 댓글이 화면에 나타나면 과제 완료입니다.

comment부분

Comment.js

import React from 'react';
import './Comment.scss';

class Comment extends React.Component {
  render() {
    const { newReply, textChange, handleSubmit } = this.props;
   //구조분해할당
    return (
      <>
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            placeholder="댓글달기..."
            onChange={textChange} //값이 바뀌면 textChange 함수실행
            value={newReply}
          />
          <button>게시</button>
        </form>
      </>
    );
  }
}

export default Comment;

좋은 웹페이지 즐겨찾기