06. Event

λ“€μ–΄κ°€κΈ°μ „

React μ—μ„œλŠ” 직접적인 DOM 의 μ ‘κ·Όλ³΄λ‹€λŠ” State λΌλŠ” μƒνƒœ 값을 μ΄μš©ν•˜μ—¬ DOM 에 λ³€ν™”λ₯Ό μ€€λ‹€κ³  ν–ˆμŠ΅λ‹ˆλ‹€. μ΄λ²ˆμ—λŠ” Event λ₯Ό ν•™μŠ΅ν•˜μ—¬ State λ₯Ό λ‹€μ–‘ν•˜κ²Œ λ³€κ²½ν•˜λŠ” 방법에 λŒ€ν•΄μ„œ μ•Œμ•„λ³΄λ €κ³ ν•©λ‹ˆλ‹€.

μ‹€μŠ΅

ν”„λ‘œμ νŠΈλŠ” 초기 μ„ΈνŒ… μƒνƒœarrow-up-right둜 μ§„ν–‰λ˜μ–΄μ§‘λ‹ˆλ‹€. +@ 둜 μ΄μ œλŠ” styled-component λ₯Ό μ΄μš©ν•˜κΈ° λ•Œλ¬Έμ— App.css 파일이 ν•„μš”μ—†μŠ΅λ‹ˆλ‹€.

μš°λ¦¬κ°€ μž…λ ₯ν•˜λŠ” 값에 λ”°λΌμ„œ 넓이, 높이, 색상을 κ°€μ§„ λ°•μŠ€λ₯Ό λ§Œλ“€μ–΄λ³΄κ³ μž ν•©λ‹ˆλ‹€.

Input 에 값을 μž…λ ₯ν•˜μ—¬ μž…λ ₯된 값을 λ°”νƒ•μœΌλ‘œ μƒμžλ₯Ό λ§Œλ“€κ³  μ‹ΆμŠ΅λ‹ˆλ‹€. λ¨Όμ € Input, Label Component λ₯Ό λ§Œλ“€μ–΄λ³΄κ² μŠ΅λ‹ˆλ‹€.

// App.js

import React from 'react'
import styled from 'styled-components'

const Label = styled.h2`
  color: #333;
`

const Input = styled.input`
  padding: 10px 20px;
`

class App extends React.Component {
  render () {
    return (
      <div>
        <Label>Width</Label>
        <Input />
        <Label>Height</Label>
        <Input />
        <Label>Color</Label>
        <Input />
      </div>
    )
  }
}

export default App

Box Component λ₯Ό μ€€λΉ„ν•©λ‹ˆλ‹€. Box λŠ” 넓이, 높이, 색상을 Prop 둜 λ°›μ•„ μŠ€νƒ€μΌμ„ κ΅¬μ„±ν•©λ‹ˆλ‹€.

μ΄λ²ˆμ—λŠ” Box μ—κ²Œ λ„˜κ²¨μ€„ State λ₯Ό μΆ”κ°€ν•©λ‹ˆλ‹€. 그리고 μΆ”κ°€λœ State λ₯Ό Box μ—κ²Œ λ„˜κ²¨μ€λ‹ˆλ‹€.

μš°λ¦¬κ°€ μ›ν•˜λŠ” 것은 Input 에 값을 μž…λ ₯ν•˜κ³  Input 에 λ§žλŠ” State κ°€ λ³€κ²½μ΄λ˜λ©΄μ„œ λ³€κ²½λœ 값이 Box μ—κ²Œ μ „λ‹¬λ˜κΈ°λ₯Ό μ›ν•©λ‹ˆλ‹€.

Input 의 onChange Event λ₯Ό μΆ”κ°€ν•˜μ—¬ λ°”λ€ŒλŠ” 값을 μΊμΉ˜ν•΄λ³΄κ² μŠ΅λ‹ˆλ‹€.

각 Input 듀은 onChange λ₯Ό 톡해 handleStyles ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•©λ‹ˆλ‹€. handleStyles ν•¨μˆ˜λŠ” event 객체λ₯Ό λ„˜κ²¨λ°›μŠ΅λ‹ˆλ‹€. event κ°μ²΄μ—λŠ” ν•΄λ‹Ή μ΄λ²€νŠΈμ— λŒ€ν•œ 정보λ₯Ό λ‹΄κ³ μžˆμŠ΅λ‹ˆλ‹€. Input 듀은 name 값을 κ°€μ§€κ³  있고 Input 이기 λ•Œλ¬Έμ— value attribute λ₯Ό κ°€μ§€κ³  μžˆμŠ΅λ‹ˆλ‹€. μš°λ¦¬λŠ” 이 값듀을 μ΄μš©ν•˜μ—¬ state λ₯Ό λ³€κ²½ν•˜λ €κ³ ν•©λ‹ˆλ‹€.

JSX μ—μ„œ Event λ₯Ό κ±Έμ–΄μ€„λ•ŒλŠ” ν•¨μˆ˜λ₯Ό JSX λ‚΄λΆ€κ°€ μ•„λ‹Œ class μ•„λž˜μͺ½μœΌλ‘œ λΉΌμ£ΌλŠ” 것이 μ’‹μŠ΅λ‹ˆλ‹€.

handleStyles ν•¨μˆ˜μ— λ„˜μ–΄μ˜€λŠ” event 객체λ₯Ό 톡해 Input 의 name κ³Ό value λ₯Ό κ°€μ Έμ˜΅λ‹ˆλ‹€.

이제 이 값듀을 μ΄μš©ν•΄μ„œ State 의 정보λ₯Ό update ν•©λ‹ˆλ‹€. State λ₯Ό update ν•  λ•ŒλŠ” λ°˜λ“œμ‹œ setState λΌλŠ” ν•¨μˆ˜λ₯Ό μ΄μš©ν•΄μ•Όν•©λ‹ˆλ‹€.

기쑴의 State 듀은 μœ μ§€ν•˜λ©΄μ„œ μƒˆλ‘œ λ“€μ–΄μ˜¨ key, value κ°’λ§Œ update ν•©λ‹ˆλ‹€.

Hook 을 μ΄μš©ν•˜κΈ°

hook 은 μœ„μ—μ„œ μ•Œμ•„λ³Έ Class Component μ™€λŠ” 살짝 λ‹€λ¦…λ‹ˆλ‹€. State μ„ μ–Έκ³Ό updateλŠ” useState λΌλŠ” 것을 μ΄μš©ν•©λ‹ˆλ‹€.

Last updated

Was this helpful?