[React] form 다루기

rondido·2022년 11월 10일
0

React

목록 보기
7/39

form 자체에서 submit을 눌렀을 때는 새로고침 되도록 되어 있다
그렇다면 어떻게 해야 새로고침을 막을 수 있을까?

<!DOCTYPE html>
<html lang="en">
    <style>
    .button {
        background-color: #4CAF50; /* Green */
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
      }
      
      .blue {background-color: #008CBA;} /* Blue */
      .red {background-color: #f44336;} /* Red */ 
      .black {background-color: #e7e7e7; color: black;} /* Gray */ 
      .gray {background-color: #555555;} /* Black */
      </style>
  <body>
    <script
      crossorigin
      src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"
    ></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    
    <div id="root"></div>

    <script type="text/babel">    
      const rootElement =document.getElementById("root");
      const App = () => {
        const handleSubmit = (event) =>{
            event.preventDefault();
            
            alert(`firstName:${event.target.value}, lastName:${event.target.value}`)
        }
        return (
        <form onSubmit={handleSubmit}>
        <label htmlFor="fname">First name:</label><br />
        <input type="text" id="fname" name="fname" defaultValue="John"/><br/>
        <label htmlFor="lname">Last name:</label><br/>
        <input type="text" id="lname" name="lname" defaultValue="Doe"/><br/><br/>
        <input type="submit" value="Submit"/>
        </form> 
        );            
    }
        
        ReactDOM.render(<App />,rootElement);
    </script>
  </body>
</html>

위 코드를 통해 나는 fristname과 lastname 가지고 오고 싶은데 alert로 evnet.target.value를 통해 뽑아왔지만 undefiend가 뜨는 것을 확인 할 수 있었다.

  • event.preventDefault()를 이용하여 기본적인 동작을 막을 수 있다.

  • console.dir를 통해 자바스크립 내에 있는 객체의 전체 구조를 알 수 있다.

  • console.log의 내용

-console.dir

console.dir를 통해 fname과 lane을 알 수 있게 되었다.
그래서 아래 코드처럼 수정해 주었다.


        const handleSubmit = (event) =>{
            event.preventDefault();
            
            alert(`firstName:${event.target[0].value}, lastName:${event.target[1].value}`)
        }

위 사진은 console.dir(event.target.elements)에 대한 내용인데 위 내용을 보고
input들을 id나 name을 가지고 타켓팅 할 수 있게 해준다는 것을 알 수 있다.

위 코드를 아래 코드처럼 변환 할 수 있다.

  const handleSubmit = (event) =>{
            event.preventDefault();
            console.dir(event.target.elements);
            alert(`firstName:${event.target.elements.fname.value}, lastName:${event.target.elements.lname.value}`)
        }

alert에서 받아올 때 input이 id나 class 둘중에 하나만 존재하여도 값을 불러 올 수 있다.

profile
개발 옆차기

0개의 댓글