티스토리 뷰

Programming

[React] 컴포넌트 반복

whilescape 2019. 12. 7. 11:55

6.1 JS 배열의 map()함수

  1. 문법

    arr.map(callback, [thisArg]);
  • callback : 새로운 배열의 요소를 생성하는 함수, 다음은 callback 함수의 params
    • currentValue : 현재 처리하고 있는 요소
    • index : 현재 처리하고 있는 요소의 index
    • array : 현재 처리하고 있는 원본 배열
  • thisArg (선택항목) : callback 함수 내부에서 사용할 this 레퍼런스
  1. 예제

    ES6 이전 문법
    var numbers =[1,2,3,4,5];
    var result = numbers.map(function(e){return e*e;});
    console.log(result);
    
    ES6 문법
    const numbers = [1,2,3,4,5];
    const result = numbers.map(e => e*e);
    console.log(result);

6.2 데이터 배열을 컴포넌트 배열로 map 하기

import React, { Component } from 'react';

class IterationSample extends Component{
    render(){
        const names =['make', 'jake', 'cake', 'sake'];
        const nameList = names.map(
            (e) => (<li>{e}</li>)
        );

     return(
         <ul>
             {nameList}
         </ul>
     )   
    }
}

export default IterationSample;

6.3 key

  1. key : 컴포넌트 배열을 렌더링했을 때, 어떤 원소에 변동이 있는지 알아내려고 사용
  2. key가 없을 때는 가상 DOM을 비교하는 과정에서 리스트를 순차-비교한다.(비효율적)
    하지만 key가 있다면 효율성 높일 수 있지.
  3. key는 unique해야 함.

6.4 application

import React, { Component } from 'react';

class IterationSample extends Component{

    state = {
        names:['make', 'jake', 'cake', 'sake'],
        name: ''
    }

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

    handleKeyPress = (e) => {
        if(e.key === 'Enter'){
            this.handleChange(e);
            this.handleInsert();

        }
    }

    handleInsert = () => {
        this.setState({
            names: this.state.names.concat(this.state.name),
            name: ''
        });
    }

    handleRemove = (index) => {
        const {names} = this.state;
        this.setState({
            names: [
                ...names.slice(0, index),
                ...names.slice(index+1, names.length)
            ]
        });
    }

    render(){

        const nameList = this.state.names.map(
            (name, index) => (
            <li 
                key={index}
                onDoubleClick={()=>this.handleRemove(index)}
                >
                {name}
            </li>
            )
        );

     return(
        <div>
            <input
                onChange={this.handleChange}
                onKeyPress={this.handleKeyPress}
                value={this.state.name}
            />
            <button onClick={this.handleInsert}>addition</button>
            <ul>
                {nameList}
            </ul>
        </div>
     )   
    }
}

export default IterationSample;

'Programming' 카테고리의 다른 글

[React] 컴포넌트 스타일링  (0) 2019.12.10
[React] 컴포넌트의 라이프 사이클  (0) 2019.12.07
[React] DOM에 이름 달기  (0) 2019.12.07
[React] 이벤트 핸들링  (0) 2019.12.06
[React] 컴포넌트  (0) 2019.12.06
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함