[ Review ] 클론코딩-인스타 메인페이지 (React)

_dodo_hee·2021년 4월 5일
0

REACT

목록 보기
3/10
post-thumbnail

props와 state에 들어가면서 분명 세션과 생활코딩을 들을땐 이해했고, 쉽다고 느꼈다. 근데 응용을 하려니 아무것도 생각이 안난다. 주말동안 props랑 state 뿌실려고 했는데.. 피로가 쌓여서 잠자고, 결국 하루 잡아서 하려니 시간이 부족하고..울고싶댜

React로 댓글구현하기

1. 초기값 세팅해주기

color: "#0094f64b"
게시버튼 색깔 초기값 색상

newComment: ""
인풋에 글을 작성할때 사용한다.

comments: [{text: "",}]
newComment에 들어온 값을 comments에 배열로 담아준다.

class Feed extends React.Component {
  constructor() {
    super();
    this.state = {
      color: "#0094f64b",
      newComment: "",
      comments: [{text: ""}]
    };
  }

2. input안에 value가져오기

statenewComment:"" setState로 작성한 값을
newCommentvalue로 들어오게 만들었다.

commentValue = (e) => {
    this.setState({
      newComment: e.target.value,
    });
  };

inputonChange={this.commentValue}를 넣어준다.

<input
  className="comment-inner"
  onChange={this.commentValue}
  value={this.state.newComment}
  type="text"
  placeholder="댓글 달기..."
/>

3. 인풋값이 들어오면 버튼 색상 활성화 하기

버튼에 style에 인풋값의 길이가 0보다 클때 색깔이 변하는 함수를 만들어준다.

<button
	className="submit"
    style={{
    	color:this.state.newComment.length > 0
        	? "#0094f6"
            : this.state.color
>
  게시
</button>

4. 버튼 누르면 댓글 추가

addCommentarr이라는 변수를 만들어주고,
arrcomments: [{text: "",}] 초기값으로 할당해주고,
arrtext: this.state.newComment를 넣어준다.

addComment 함수가 실행되면 값이 바뀐다.
commentsarr에 푸시된 배열이 들어온다.

그리고 input값에 있는 onChange={this.commentValue}
newComment input에 입력한 값이 들어온다.

실행 후 setState로 인하여 arrnewComment: ""가 실행된다.
""를 사용하는 이유는 댓글을 달고나서 다시 인풋값을 초기화 해주기 위해서이다.

addComment = () => {
    let arr = this.state.comments;
    arr.push({
      text: this.state.newComment,
    });

    this.setState({
      comments: arr,
      newComment: "",
    });
  };

버튼에 onClick={this.addComment} 을 넣어준다.

<button
	className="submit"
    onClick={this.addComment}
>
  게시
</button>

5. 엔터키를 치면 댓글 추가하기

키값이 엔터면 addComment함수를 실행시킨다.
그 후에 입력한 인풋값을 ""로 초기화 시켜 아무것도 없게 만든다.

pressEnter = (e) => {
    if (e.key === "Enter" && this.state.newComment) {
      this.addComment();
      e.target.value = "";
    }
  };

인풋에 onKeyPress={this.pressEnter}를 넣어준다.

<input
	className="comment-inner"
    onChange={this.commentValue}
    onKeyPress={this.pressEnter}
    value={this.state.newComment}
    type="text"
    placeholder="댓글 달기..."
       />

6. li자리(댓글이 올라 갈 자리)에 추가하기

li가 들어 갈 자리에 replies: [{text: "",},] 배열에 .map을 사용한다.
myco은 내가 입력한 인풋값이되고,
<li>{myco.text}</li> 인풋값과 .text 를 넣어서 실행시
li가 하나씩 추가되게 하였다.

<ul className="content-write">
  <li>
    <span className="chat-id">_dodo_hee</span>
    <span className="chat-content">까눌레 엉엉😭</span>
  </li>
  {this.state.comments.map((myco) => (
  <li>{myco.text}</li>
  ))}
</ul>

.map()

map() 함수는 각 배열의 요소를 돌면서 인자로 전달된 함수를 사용하여 처리 된 새로운 결과를 새로운 배열에 담아 반환하는 함수


{this.state.comments.map((myco) => (
  <li>{myco.text}</li>
  ))}

push해서 담아준 인풋값이 들어있는 배열 요소가 들어올때마다 내가 입력한 인풋값을 인자로 받아서
내가 입력한 인풋값을 텍스트로 가져온 값을 li안에 넣어서 반환시켜라는 뜻.



진짜 아무리 구글링 하고 따라해보고 다했는데도 안됐는데 이해도 너무 안됐었는데..
한줄기 빛같은 블로그가 날 도왔다...개발초보님 블로그
나는 이해가 안되면 복붙조차도 못하는 타입이다..어떻게 어디에 복붙해놔야할지도 몰라서
근데 개발초보님 블로그보고 너무 이해도 잘되고 쉽게 설명해놓으셨다.
더더욱 평일 내내 리액트 세션 복습이랑 인강으로 클론코딩으로 감을 익혀야 할 것 같다..

profile
무럭무럭 자라나는 도도 개발성장일기

0개의 댓글