codestates / codestates/BanThing
[Error Handling] button onClick 에러
- Dominant language
- TypeScript
- Stars
- 0
- Forks
- 2
- PR merge metrics
- No merged PRs in 30d
Description
### 어떤 에러인가요?

자바스크립트에서는 당연히 되었던 onClick이벤트가 typeScript에서는 타입의 오류로 작동하지 않는다.
- 에러 메시지
```
$ 터미널의 에러 코드를 여기 넣어주세요.
```
### 에러 핸들링 방법
- 먼저 기존의 코드인
```
function Button({ name, children }: buttonType) {
return {children}
```
```
function Button({ name, children }: BasicButtonProp) {
return (
{children}
)
```
- 이렇게 수정해 주었습니다. 왜 오류가 났는지 추론을 해보자면 onClick의 타입은 React.MouseEventHandler로type MouseEventHandler = EventHandler>; 마우스에 관한 이벤트만 관리해주는 것 같다.
```
interface MouseEvent extends UIEvent {
altKey: boolean;
button: number;
buttons: number;
clientX: number;
clientY: number;
ctrlKey: boolean;
/**
* See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method.
*/
getModifierState(key: string): boolean;
metaKey: boolean;
movementX: number;
movementY: number;
pageX: number;
pageY: number;
relatedTarget: EventTarget | null;
screenX: number;
screenY: number;
shiftKey: boolean;
}
```
- 살펴보니 마우스의 이벤트에 관련된 정보들을 볼 수 있다. 별 도움은 되지 않는 것 같다.
- 다음으로 HTMLButtonElement로가면
```
interface HTMLButtonElement extends HTMLElement {
disabled: boolean;
type: string;
value: string;
...
}
```
- 버튼에 관련된 다양한 리턴 값들을 볼 수 있습니다. 현재 저는 버튼을 눌렀을 때 그 버튼을 포함한 container를 console.log()로 불러오고 싶으니 value에 containerName을 설정해주자
```
const handleClick = (event: React.MouseEvent) => {
event.preventDefault()
const button: HTMLButtonElement = event.currentTarget
console.log(button.value)
}
function Button({ containerName, children }: BasicButtonProp) {
return (
{children}
)
}
```

잘 작동되는 것을 볼 수 있다.
### 에러 핸들링을 위해 참고한 레퍼런스 링크
- Memory-It 의 Error Handling 예시입니다.
[블로그](https://www.kindacode.com/article/react-typescript-handling-onclick-event/)
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.