리액트와 타입스크립트의 도움을 이용해 form을 구현할 것이다.
React.FormEvent<HTMLInputElement>을 작성해줌으로써, 타입스크립트는 이 함수가 InputElement에 의해서 실행될 것을 알게 된다.
function onChange (event: React.FormEvent<HTMLInputElement>){
console.log(event.currentTarget.value);
const {
currentTarget: { value }
} = event;
setValue(value);
}
모두 이벤트가 작동되는 엘리먼트를 의미한다. 다른점은 타입스크립트에서는 currentTarget을 사용할 뿐이다.
const {} = event;
//event를 연다.
const { currentTarget: { value } } = event;
그리고 안쪽에 currentTarget의 value를 얻어 올것이다.
결론은, 구조분해할당이다.
onSubmit 또한 하나의 event이다.
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
console.log("hello", value);
}
return (
<div>
<form onSubmit={onSubmit}>
<input
type="text"
placeholder="username"
value={value}
onChange={onChange}
/>
<button>Log In</button>
</form>
</div>
);
}
export default App;
value는 엔터키를 누르거나 버튼클릭시 전송되는 값을 의미한다.
import React, { useState } from "react";
import styled from "styled-components";
function App() {
const [value, setValue] = useState("");
function onChange (event: React.FormEvent<HTMLInputElement>){
// console.log(event);
console.log(event.currentTarget);
console.log(event.currentTarget.value);
const {
currentTarget: { value }
} = event;
setValue(value);
}
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
console.log("hello", value);
}
return (
<div>
<form onSubmit={onSubmit}>
<input
type="text"
placeholder="username"
value={value}
onChange={onChange}
/>
<button>Log In</button>
</form>
</div>
);
}
export default App;