一、DOM 事件类型声明示例
1. 鼠标点击事件(`MouseEvent`)
使用 React.MouseEvent<HTMLButtonElement> 定义
javascript
import React from "react";
const MyComponent: React.FC = () => {
const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
// 这里可以访问MouseEvent的相关属性,比如获取鼠标点击的坐标
console.log("Client X:", event.clientX);
console.log("Client Y:", event.clientY);
};
return <button onClick={handleClick}>Click Me</button>;
};
export default MyComponent;
2. 键盘输入事件(`KeyboardEvent`)
使用 React.KeyboardEvent<HTMLInputElement> 定义
javascript
import React from "react";
const MyComponent: React.FC = () => {
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Enter") {
console.log("用户按下了回车键");
}
};
return <input onKeyDown={handleKeyDown} placeholder="请输入内容" />;
};
export default MyComponent;
3. 表单提交事件(`FormEvent`)
使用 React.FormEvent<HTMLFormElement> 定义
javascript
import React from "react";
interface FormData {
username: string;
password: string;
}
const MyComponent: React.FC = () => {
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData: FormData = {
username: (
event.currentTarget.elements.namedItem("username") as HTMLInputElement
).value,
password: (
event.currentTarget.elements.namedItem("password") as HTMLInputElement
).value,
};
console.log("提交的表单数据:", formData);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="username" placeholder="用户名" />
<input type="password" name="password" placeholder="密码" />
<button type="submit">提交</button>
</form>
);
};
export default MyComponent;