React - instagram

Jungyub Song·2020년 5월 18일
0

1. Login page

1) 우선 '로그인' 버튼 클릭 시 Login page에서 Main page로 넘어가게 하기 위해 button에 onClick event handler를 주었고, 이에 대한 조건은 ID 부분에 @가 포함되어야 하고, PW의 length가 4 이상일 때로 설정하였다.

2) 또한, 동일 조건에서 로그인 버튼의 색깔 변화를 주어 활성화/비활성화를 구분하였으며, 이는 className을 setState로 변경하는 것으로 구현하였다.

  setBtColor = () => {
    if (this.state.idInput.includes("@") && this.state.pwInput.length > 4) {
      this.setState({btColor: "bt_item2"})
    } else {
      this.setState({btColor: "bt_item1"})
    }
  }
 // 초기 this.state 값은 "bt_item1"

3) 실제 입력되는 idInput과 pwInput 값을 확인하기 위해 onChange={this.handleChange} 이벤트를 생성하였고, 해당 함수에 setState를 통해 ""값이 value값으로 채워질 수 있도록 설정하였다.

4) 버튼 색상 변경에 대한 함수를 handleChange 함수에 넣음으로써 idInput이나 pwInput 값이 setBtColor 조건과 일치할 경우 버튼 색상이 변경될 수 있도록 하였다.

  handleChange = e => {
    this.setState({ [e.target.name]: e.target.value }, () => this.setBtColor());    
  } 

2. Main page

* Feeds_comment (부모 컴포넌트)

* Comment (자식 컴포넌트)

1) 우선 '게시' 버튼에 postComment 함수가 담긴 onClick event를 주어 해당 버튼을 클릭할 경우 input value에 담긴 CommentText를 빈 배열에 담아주고 해당 내용을 setState하게 만들었다.

  postComment = e => {
    e.preventDefault()
    if (this.state.commentText.length > 0) {
      let Arr = this.state.commentArr;
      Arr.push(this.state.commentText);
      this.setState({commentArr: Arr});
      this.setState({commentText: ""}, () => this.setBtColor());
    }
  }

2) Length > 0이라는 조건에 따라 버튼 색상이 변경되는 것은 login page와 동일한 방식으로 구현하였다.

  setBtColor = () => {
    if (this.state.commentText.length > 0) {
      this.setState({btColor: "upload2"})
    } else {
      this.setState({btColor: "upload1"})
    }
    
  }

3) input 태그에 onChange event를 주어 그 안에 handleChange 함수를 적용하였고, 해당 함수는 input value값을 업데이트 시키는 기능을 하였다. 이 지점에서 console.log를 찍어보면 내가 input란에 입력하는 값이 실시간으로 보여지게 된다.

4) 마지막으로 빈 배열에 담긴 CommentText를 지정한 위치에 뿌려주는 기능을 구현할 차례이다.
이는 해당 배열을 map으로 각각 전달해주는 것을 의미하며, render() 안에 다음과 같이 작성하였다.

const comment = this.state.commentArr.map((element, i) => {return <Comment text = {element} key = {i}/>})

빈 배열의 각 element를 Comment(자식) 컴포넌트에 mapping하고, 그 중에서도 text라는 props를 설정하여 Comment 컴포넌트의 msg 부분에 넣어주게 지정하였다.
때문에 사용자가 입력한 하나의 value가 element가 되어 Comment 컴포넌트의 msg 부분에 업데이트 되는 것이다. 변경사항이 없는 id와 icon_heart 부분은 자동으로 게시되며, props로 주었던 msg 부분만 setStat되며 업로드 되는 것이다.
또한, enter키에도 게시가 될 수 있도록 해당 input과 button 태그를 form 태그로 감쌌으며, 이에 따른 페이지 reload되는 것을 방지하기 위해 postComment 함수에 e.preventDefault()를 넣어주었다.

0개의 댓글