Study/TypeScript
[TypeScript] TypeScript & React SyntheticEvent(합성이벤트)
갈푸라떼
2022. 7. 22. 18:31
* [참고] https://ko.reactjs.org/docs/events.html
import React, { useState } from "react";
import "./App.css";
function App() {
const [value, setValue] = useState("");
const handleValue = (e: React.FormEvent<HTMLInputElement>) => {
setValue(e.currentTarget.value);
};
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {};
const onClick = (e: React.MouseEvent<HTMLButtonElement>) => {};
return (
<div>
<form onSubmit={onSubmit}>
<input
type="text"
placeholder="username"
value={value}
onChange={handleValue}
/>
</form>
<button onClick={onClick}>Click</button>
</div>
);
}
export default App;
- React.event이름.이벤트를 발생시키고 있는 Element 이름
- form안에서 있는 input에서 event가 발생하고 있으므로 FormEvent<HTMLInputElement>로 type을 지정해준다.
- form에서 event가 발생하고 있으므로 FormEvent<HTMLFormElement>로 type을 지정해준다.
- button은 form안에서 동작하고 있지 않기 때문에 MouseEvent<HTMLButtonElement>로 type를 지정해준다.