WHAT - Typescript 定义元素类型
文章目录
- 1. 原生 JavaScript 中(TypeScript)
- 示例
- 常见类型对应表
- 2. 在 React 中(使用 React.RefObject 和事件中访问)
- A. 使用 useRef 获取元素类型
- B. 在事件处理函数中
- C. 其他事件类型示例
- 3. 在 Vue 中(Vue 3 + TypeScript)
- A. 使用模板 ref 和 onMounted
- B. 在事件中使用
- 小结对比
在 TypeScript 中,为 DOM 元素定义类型是一个常见需求,不同场景(原生 JavaScript、React、Vue)下写法略有不同,下面为你详细列出:
1. 原生 JavaScript 中(TypeScript)
在 TypeScript 中操作原生 DOM 元素,常用类型来自 lib.dom.d.ts
中定义的类型,例如 HTMLInputElement
, HTMLDivElement
, HTMLElement
等。
示例
const input = document.querySelector('input') as HTMLInputElement;
input.value = 'Hello';
或更安全写法(避免 null
):
const input = document.querySelector('input');
if (input instanceof HTMLInputElement) {
input.value = 'Hello';
}
常见类型对应表
元素 | 类型 |
---|---|
<input> | HTMLInputElement |
<textarea> | HTMLTextAreaElement |
<select> | HTMLSelectElement |
<div> | HTMLDivElement |
<button> | HTMLButtonElement |
所有元素 | HTMLElement |
2. 在 React 中(使用 React.RefObject 和事件中访问)
A. 使用 useRef 获取元素类型
import React, { useRef, useEffect } from 'react';
const MyComponent: React.FC = () => {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
return <input ref={inputRef} />;
};
B. 在事件处理函数中
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
};
C. 其他事件类型示例
事件类型 | 类型名 |
---|---|
onChange on input | React.ChangeEvent<HTMLInputElement> |
onClick | React.MouseEvent<HTMLElement> |
onSubmit on form | React.FormEvent<HTMLFormElement> |
onKeyDown on textarea | React.KeyboardEvent<HTMLTextAreaElement> |
3. 在 Vue 中(Vue 3 + TypeScript)
A. 使用模板 ref 和 onMounted
<template>
<input ref="inputEl" />
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
const inputEl = ref<HTMLInputElement | null>(null);
onMounted(() => {
if (inputEl.value) {
inputEl.value.focus();
}
});
</script>
B. 在事件中使用
<template>
<input @input="handleInput" />
</template>
<script lang="ts" setup>
const handleInput = (e: Event) => {
const target = e.target as HTMLInputElement;
console.log(target.value);
};
</script>
小结对比
框架 / 场景 | 写法方式 | 类型示例 |
---|---|---|
原生 JS + TS | as HTMLInputElement / instanceof | HTMLDivElement , HTMLInputElement |
React | useRef<HTMLInputElement>() | React.ChangeEvent<HTMLInputElement> |
Vue | `ref<HTMLInputElement | null>()` |