Event.target이 Typescript의 요소가 아닌 이유는 무엇입니까?
난 그냥 내 아이로 이걸 하고 싶어.KeyboardEvent
var tag = evt.target.tagName.toLowerCase();
하는 동안에Event.target종류EventTarget에서는 상속되지 않습니다.Element그래서 이렇게 캐스팅을 해야 돼요.
var tag = (<Element>evt.target).tagName.toLowerCase();
이는 일부 브라우저가 표준을 준수하지 않기 때문일 수 있습니다.TypeScript에서 브라우저에 구애받지 않는 올바른 구현은 무엇입니까?
p.s. jQuery를 사용하여 캡처하고 있습니다.KeyboardEvent.
JLRishe의 답변이 정확하기 때문에 이벤트 핸들러에서 다음과 같이 사용합니다.
if (event.target instanceof Element) { /*...*/ }
로부터 상속되지 않는다.Element왜냐하면 모든 이벤트타깃이 요소는 아니기 때문입니다.
MDN에서:
요소, 문서 및 창이 가장 일반적인 이벤트타깃이지만 XMLHttpRequest, AudioNode, AudioContext 등 다른 오브젝트도 이벤트타깃이 될 수 있습니다
심지어KeyboardEvent사용하려고 하는 것은 DOM 요소나 윈도 오브젝트(및 이론적으로 다른 것)에서 발생할 수 있기 때문에, 여기서의 조작은 의미가 없습니다.evt.target로 정의되다Element.
만약 DOM 요소에 대한 이벤트라면, 당신은 안전하게 추측할 수 있습니다.evt.target.는Element크로스 브라우저 동작의 문제는 아닌 것 같습니다.그것만EventTarget보다 추상적인 인터페이스입니다.Element.
자세한 것은, https://github.com/Microsoft/TypeScript/issues/29540 를 참조해 주세요.
타이프 스크립트를 사용하여 기능에만 적용되는 커스텀 인터페이스를 사용합니다.사용 사례의 예.
handleChange(event: { target: HTMLInputElement; }) {
this.setState({ value: event.target.value });
}
이 경우 handleChange는 HTMLInputElement 유형의 타깃필드를 가진 객체를 수신합니다.
코드 후반부에서 사용할 수 있습니다.
<input type='text' value={this.state.value} onChange={this.handleChange} />
보다 깔끔한 접근방식은 인터페이스를 다른 파일에 저장하는 것입니다.
interface HandleNameChangeInterface {
target: HTMLInputElement;
}
나중에 다음 함수 정의를 사용합니다.
handleChange(event: HandleNameChangeInterface) {
this.setState({ value: event.target.value });
}
제 use 케이스에서는 Change를 처리할 수 있는 유일한 발신자는 HTML 요소 유형의 입력 텍스트라고 명시적으로 정의되어 있습니다.
타입스크립트 3.2.4
속성을 검색하려면 대상을 적절한 데이터 유형으로 캐스팅해야 합니다.
e => console.log((e.target as Element).id)
확장 가능한 범용 인터페이스를 직접 만들 수 있습니까?Event이런 거?
interface DOMEvent<T extends EventTarget> extends Event {
readonly target: T
}
그런 다음 다음과 같이 사용할 수 있습니다.
handleChange(event: DOMEvent<HTMLInputElement>) {
this.setState({ value: event.target.value });
}
타이프 스크립트를 사용하면 다음과 같이 타입 에일리어스를 활용할 수 있습니다.
type KeyboardEvent = {
target: HTMLInputElement,
key: string,
};
const onKeyPress = (e: KeyboardEvent) => {
if ('Enter' === e.key) { // Enter keyboard was pressed!
submit(e.target.value);
e.target.value = '';
return;
}
// continue handle onKeyPress input events...
};
@Bangonkali는 올바른 답을 제공하지만, 이 구문이 더 읽기 쉽고 더 좋은 것 같습니다.
eventChange($event: KeyboardEvent): void {
(<HTMLInputElement>$event.target).value;
}
Angular 10 이상 사용자용
HTML Input Element를 선언하고 확장하여 아래 부트스트랩 4+ 파일브라우저 입력에서와 같이 타겟을 오브젝트로 사용합니다.이렇게 하면 많은 작업을 절약할 수 있습니다.
selectFile(event: Event & { target: HTMLInputElement}) {
console.log(event.target.files);
this.selectedFile = event.target.files[0];
}
이 하게 됩니다.input드, 키, 업, 키, 키, 키.그러나 이벤트는 어디서든 발생할 수 있습니다. 「 」, 「 」keyup에 접속합니다.document 있는 「」는 value정보를 올바르게 제공하기 위해 다음과 같은 추가 유형을 제공합니다.
interface KeyboardEventOnInputField extends KeyboardEvent {
target: HTMLInputElement;
}
...
onKeyUp(e: KeyboardEventOnInputField) {
const inputValue = e.target.value;
...
}
이 '인 Event 실제로 것인지, 를 들어 ''가할 수
onKeyUp(e: Event) {
const evt = e as KeyboardEventOnInputField;
const inputValue = evt.target.value;
this.inputValue.next(inputValue);
}
이것은 예를 들어 Angular에서 필요합니다.
https://stackoverflow.com/a/48443771/5515861과 https://stackoverflow.com/a/58806863/5515861의 답변은 맞지만 더 좋은 방법이 있습니다.예를들면
// in another file
export interface DOMEvent<T extends EventTarget> extends Event {
readonly target: T;
}
onFileChange(event: Event): void {
const { target } = event as DOMEvent<HTMLInputElement>;
if (target.files && target.files.length > 0) {
// do something with the target
}
}
나는 이것을 사용한다.
onClick({ target }: MouseEvent) => {
const targetElement: HTMLElement = target as HTMLElement;
const listFullHeight: number = targetElement.scrollHeight;
const listVisibleHeight: number = targetElement.offsetHeight;
const listTopScroll: number = targetElement.scrollTop;
}
언급URL : https://stackoverflow.com/questions/28900077/why-is-event-target-not-element-in-typescript
'programing' 카테고리의 다른 글
| "모듈 외부에서 Import 문을 사용할 수 없습니다"를 해결하는 방법 (0) | 2023.03.04 |
|---|---|
| orderBy가 예상대로 작동하지 않음:Angularjs (0) | 2023.03.04 |
| 타입 프렌들리 주사란 무엇입니까? (0) | 2023.03.04 |
| Axios를 사용한 액세스 제어 오리진 헤더 오류 (0) | 2023.03.04 |
| wp_localize_script가 작동하지 않습니다. (0) | 2023.03.04 |