유형 스크립트의 대응 이벤트 유형
사용할 때 React/Types 스크립트 앱을 만들 수 없는 경우MouseEvent내 이벤트 핸들러에 입력:
private ButtonClickHandler(event: MouseEvent): void
{
...
}
이해합니다.
error TS2322: Type '{ onClick: (event: MouseEvent) => void; children: string; }' is not assignable to type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>'.
Type '{ onClick: (event: MouseEvent) => void; children: string; }' is not assignable to type 'ButtonHTMLAttributes<HTMLButtonElement>'.
Types of property 'onClick' are incompatible.
Type '(event: MouseEvent) => void' is not assignable to type 'EventHandler<MouseEvent<HTMLButtonElement>>'.
Types of parameters 'event' and 'event' are incompatible.
Type 'MouseEvent<HTMLButtonElement>' is not assignable to type 'MouseEvent'.
Property 'fromElement' is missing in type 'MouseEvent<HTMLButtonElement>'.`
저도 노력했습니다.MouseEvent<HTMLButtonElement>하지만 그 후에error TS2315: Type 'MouseEvent' is not generic..
왜요?
내 것에서 발췌package.json:
"devDependencies": {
"@types/react": "^16.0.7",
"@types/react-dom": "^15.5.5",
"ts-loader": "^2.3.7",
"typescript": "^2.5.3",
"webpack": "^3.6.0"
},
"dependencies": {
"react": "^16.0.0",
"react-dom": "^16.0.0"
}
#1 편집:
바인딩 인render():
<button onClick={ this.ButtonClickHandler }>Toggle</button>
에constructor:
this.ButtonClickHandler = this.ButtonClickHandler.bind(this);
여기서 일어나는 일은 두 가지 유형을 사용할 수 있다는 것입니다.MouseEventfrom jsx/lib/js/js/web.jsx(유형 매개 변수가 없음) 및React.MouseEvent<T>from @types/parameter/index.d.ts(하나의 형식 매개 변수,T요소의 유형).유형 스크립트는 구조적 유형을 사용하므로 서로 다른 유형이라도 호환될 수 있습니다.하지만 그것과 호환되기 위해서는.onClickReact의 버전을 사용해야 하는 핸들러(해당 유형 포함)T(HTMLElement이 핸들러를 연결할 요소를 알고 있으면 작동하거나 더 구체적으로 말할 수 있습니다.
그렇게event: MouseEvent실패 이유:onClick에는 이벤트 유형의 특수 버전이 필요합니다. event: MouseEvent<HTMLElement>그것은 잘못된 것을 가리키기 때문에 실패합니다.MouseEvent형식 매개 변수가 없는 형식입니다. React.MouseEvent<HTMLElement>적절한 유형을 얻고 필요한 매개 변수를 지정하면 결과 유형이onClick핸들러
나는 같은 문제를 가지고 있었지만 명확하게 가져오기를 통해 해결할 수 있었습니다.MouseEvent부터React
저는 이것에 대한 오류를 가지고 있었습니다.
import React from 'react';
하지만 이것으로 고정되었습니다.
import React, { MouseEvent } from 'react';
믿을 수 없을 겁니다.생성자 할당을 렌더 함수로 이동하기에 충분했습니다.
render()
{
return (
<button onClick={ this.Button_Click.bind(this) }>Toggle</button>
)}
그리고나서MouseEvent사용할 수 있게 됩니다.
private Button_Click(event: MouseEvent): void
왜 이런 일이 일어날까요?
언급URL : https://stackoverflow.com/questions/46524815/react-event-type-in-typescript
'programing' 카테고리의 다른 글
| Excel 워크북의 코드 보호? (0) | 2023.07.10 |
|---|---|
| Oracle 10g - NULL이 아닌 곳 최적화 (0) | 2023.07.10 |
| null 값을 바꾸는 동안 두 행을 하나로 병합 (0) | 2023.07.10 |
| 파이썬 유닛 테스트를 위해 mongodb를 조롱하는 방법은 무엇입니까? (0) | 2023.07.10 |
| Oracle Database에서 SQL을 사용하여 XML Clob에서 데이터 추출 (0) | 2023.07.10 |