티스토리 뷰

활동/교육과정 중 기록

200206 React

Stolen Moments 2020. 2. 6. 16:50

React




JSX를 알아보자 -ㅅ-



- 예제 : 할 일 목록 


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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import React from 'react'
 
class MyComponent extends React.Component {
    state = {
        desc: '', id: 0, todoList: []
    }
 
    // 할 일 추가
    todoAdd = () => {
        // id 증가
        // 설명 입력
        // 추가
        let { desc, id, todoList } = this.state;
 
        id += 1
        this.setState({ id })
 
        todoList.push({ desc, id })
        console.dir(todoList)
        alert(`${desc} 추가`)
    }
    // 할 일 삭제
    todoDel = (e) => {
        const { todoList } = this.state
        const id = Number(e.target.dataset.id)
        {/* e.target.dataset.id는 data-id를 가리킨다. */}
        const before = todoList.filter(todo => todo.id === id)
 
        alert(`${before[0].desc} 삭제`)
 
        const newTodoList = todoList.filter(todo => todo.id !== id)
        this.setState({ todoList: newTodoList })
    }
 
    onChangeDesc = e => {
        this.setState({ desc: e.target.value })
    }
 
    render() {
        let { todoList } = this.state;
 
        return (
            <div>
                <h2>할 일 목록이다</h2>
                <ul>
                    {
                        todoList.map(todo => {
                            return (
                                <li key={todo.id}>
                                    <span>{todo.desc}</span> {/* data-id는 JSX 문법 */}
                                    <button data-id={todo.id} onClick={this.todoDel}>삭제</button>
                                </li>
                            )
                        })
                    }
                </ul>
                <input type="text" id="inputTodo" onChange={this.onChangeDesc}></input>
                <button onClick={this.todoAdd}>추가</button>
            </div>
        )
    }
}
 
export default MyComponent
cs



e.target : onChange 메소드가 호출된 곳의 태그 부분을 가져오더라.


onChangeDesc에서 e.target = <input type="text id="inputTodo">


그러므로 e.target.value는 input 영역의 텍스트.

반응형

'활동 > 교육과정 중 기록' 카테고리의 다른 글

200211 React  (0) 2020.02.11
200207 React  (0) 2020.02.07
200205 React, JavaScript  (0) 2020.02.05
200204 React  (0) 2020.02.04
200129 JavaScript, jQuery  (0) 2020.01.29
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   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
글 보관함