Front-end/React

React - input

Cuvely 2023. 5. 1. 00:59
728x90
반응형

React input

React JSX 에서 input태그를 html태그처럼 사용할 수 있다.

// html input 태그와 조금 다르게 닫는 태그도 설정
<input type="타입선언"></input>

// 또는
<input type="타입선언"/>

JSX 에서 input 태그 사용하는 다른점닫는 태그를 사용해야 한다.

 

값을 입력할 때 마다 input 을 제어하려면 onChange 이벤트핸들러를 사용해 제어할 수 있다.

/* eslint-disable */

import logo from './logo.svg';
import './App.css';
import { useState } from 'react';


function App() {

  let postId = 'postId';
  let [title, setTitle] = useState(['Title1', 'Title2', 'Title3']);
  let [blogTItle, setBlogTitle] = useState('ReactBlog');
  let [like, changeLike] = useState([0, 0, 0]);
  let [modal, setModal] = useState(false);
  let [detailTitle, setDetailTitle] = useState(0);
  let [inputVal, setInputVal] = useState('');

  return (
    <div className="App">
      <div className="black-nav">
        <h4 id={postId} style={{ color: 'red', fontSize: '16px' }}>{blogTItle}</h4>
      </div>

      {
        title.map(function (item, idx) {
          return (
            <div className="list" key={idx}>
              <h4 onClick={() => {
                setModal(true);
                setDetailTitle(idx);
              }}>{item} <span onClick={() => {
                let copyLike = [...like];
                copyLike[idx] += 1;
                changeLike(copyLike);
              }}>❤</span> {like[idx]} </h4>
              <p>4월 26일</p>
            </div>)
        })
      }

      <input onChange={() => {	// onChange를 사용해 입력할때마다 1을찍는다
        console.log(1);
      }}></input>

      {modal === true ? <Modal setTitle={setTitle} title={title} detailTitle={detailTitle} ></Modal> : null}

    </div>
  );
}


function Modal(props) {
  return (
    <div className='modal'>
      <h4>{props.title[props.detailTitle]}</h4>
      <p>날짜</p>
      <p>상세내용</p>
      <button onClick={() => {
        let copy = [...props.title];
        copy[0] = 'My Title1';
        props.setTitle(copy);
      }}>Edit Title</button>
    </div>
  );
}

export default App;

 

 

 

반응형

 

 

 

input 에 입력한 값을 가져오려면 onChage 핸들러파라미터를 추가하여 태그를 제어하면 값을 가져올 수 있다.

<input onChange={(e) => {	// 파라미터 e를 추가한다.
  console.log(e.target.value); // e속성에 있는 target에서 value를 가져온다.
}}></input>

 

입력한 값을 state에 저장하여 가져올 수 도있다.

      // useState를 생성한다.
      let [inputVal, setInputVal] = useState('');
      
      <input onChange={(e) => {
        // 입력할 때 마다 state에 저장한다.
        setInputVal(e.target.value);
        
        // state에 저장된 값을 콘솔에 보여준다.
        console.log(inputVal);
      }}></input>

 

맨 처음에 빈 값이 생성되는 이유는 React에서 state값저장하는 함수비동기 처리로 실행되어서 setInputVal(e.target.value)가 완료 되기전에 console.log 가 실행이 되어 빈 값이 찍힌 후 하나씩 값이 보여진다.

728x90
반응형