TIL 86 l .map() 메서드가 react에서 사용될 때

YB.J·2021년 10월 30일
0

React

목록 보기
3/4
post-thumbnail

.map() 메서드가 react에서 사용될 때..

.map() 메서드란?

  • map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.
  • .map() 메서드는 그 앞의 배열(arary1)을 인자로 받아서 함수를 실행한다.
const array1 = [1, 4, 9, 16];

const map1 = array1.map(x => x * 2);

console.log(map1);

[2, 8, 18, 32]

출처: MDN Web Docs(https://developer.mozilla.org)

.map() 메서드를 react에서 활용해보자

  • this.state : MainFeeds의 상태를 정의

    • this.state.first의 상태는 ''(빈문자열)이다
    • this.state.commentLists의 상태는 [] 빈 배열이다
  • onChange={this.commentWrite}

    • onChange 이벤트가 발생하면, comentWrite 함수가 실행된다. 이 때, e.target.value 값을 통하여 이벤트 객체(input창)에 담겨있는 텍스트 값(type=text)을 읽어올 수 있다. comentWrite 함수가 작동하면 input창을 target으로 하여서 input창의 value를 가져오기 때문.
  • onClick={this.commentOut}

    • 버튼을 클릭하는 이벤트가 발생하면(onClick) commentOut 함수가 실행된다. 이 때, this.state.commentLists의 원래 값인 빈 배열이 concat을 통해 복사되었다가, this.state.first값(input창에 들어와서 읽힌 값)이 배열에 들어가서 commentLists에 저장된다.
    • 그리고 그 다음 줄 first가 실행된다(input 창의 값이 빈 문자열로 저장된다)
  • {this.state.commentLists.map(el => { return()}

    • this.state.commentLists를 인자로 받은 .map()이 함수를 실행하여 return한다
    • li 태그 밑에 {el}이 인자가 들어갈 자리이다
class MainFeeds extends Component {
  constructor(props) {
    super(props);
    this.state = {
      first:‘’,
      commentLists :[],
    };
  }
  
  commentWrite= (e) => {
    this.setState({
      input:e.target.value,
      })
  }
  
 commentOut = () => {
   this.setState({
     commentLists:this.state.commentLists.concat(this.state.first),
     first:‘’
 })
}
  render() {
    return (
      <>
        <main className=“mainContainer”>
          <article>
            <section className=“feed”>
              <div className=“commentWrapper”>
                <ul id=“commentLists”>
                  {this.state.commentLists.map(el => {
                    return(
                   <li>
                     <span className=“name”>연비</span>&nbsp;
                     <span>{el}</span>
                    </li>
                    )
                   } )}
                </ul>
              </div>
              <div className=“comment”>
                <input
                  id=“commentInput”
                  type=“text”
                  value={this.state.first}
                  placeholder=“댓글 달기...”
                  onChange={this.commentWrite}
                />
                <button id=“submit” onClick={this.commentOut}>
                  게시
                </button>
              </div>
            </section>
          </article>
        </main>
      </>
    );
  }
}
export default MainFeeds;
profile
♪(^∇^*) 워-후!!(^∀^*)ノシ

0개의 댓글