티스토리 뷰

HTML 폼 엘리먼트는 폼 엘리먼트 자체가 내부 상태를 가지기 때문에, React의 다른 DOM 엘리먼트와 다르게 동작

사용자가 폼을 제출하면 새로운 페이지로 이동하는 기본 HTML 폼 동작을 수행

 

제어 컴포넌트 (Controlled Component)

<input>, <textarea>, <select>와 같은 폼 엘리먼트는 일반적으로 사용자의 입력을 기반으로 자신의 state를 관리하고 업데이트

 React에서는 변경할 수 있는 state가 일반적으로 컴포넌트의 state 속성에 유지되며 setState()에 의해 업데이트

 

<input>

1. type = "text" 

 

<input type="text" value={txtValue} onChange={(e) => { setTxtValue(e.target.value); }} />

 

cf) defaultValue <- Uncontrolled Components 

<input type="text" defaultValue={"example"} />

 

 

2. checkbox 

<input type = "checkbox" checked = {checkValue} onChange = {(e) => setCheckValue(e.target.checked)} />

cf) defaultValue?

Likewise, <input type="checkbox"> and <input type="radio"> support defaultChecked, and <select> and <textarea> supports defaultValue.

 

3. radio

2.1 radio (two) 

<input type="radio" name="radio1" checked={checkRadio} onChange={(e) => setCheckRadio(true)} />
<input type="radio" name="radio1" checked={!checkRadio} onChange={(e) => setCheckRadio(false)} />

 

3.2. radio (more than three)  

 {radioTxt.map((radioTxt, index) => (
      <div key={index}>
        <input
          id={"radio_" + (index + 1)}
          type="radio"
          name="radio"
          defaultChecked={radioValue}
          onChange={() => setRadioValue(radioTxt)}
        />
      </div>
    ))

 

 

<textarea>  

<textarea type="text" maxLength={50} value={txtAreaValue} onChange={(e) => { setTxtAreaValue(e.target.value); }} />

 

 

비제어  컴포넌트 (Controlled Component)

대부분 경우에 폼을 구현하는데 제어 컴포넌트를 사용하는 것이 좋음 

대안인 비제어 컴포넌트는 DOM 자체에서 폼 데이터가 다루어짐 

 

 

1. <input type = "text" >의 defaultValue 

<input type="text" defaultValue={"example"} />

 

 

2. <input type = "file">

<input type="file" ref={fileInput} />

 

 

전체코드는 여기에 

 

 

 

 

 

출처 

1. https://ko.reactjs.org/docs/forms.html

2. https://ko.reactjs.org/docs/uncontrolled-components.html

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함