React之ts类型标注汇总
# 1、为函数组件标注 props 类型,并设置默认值
import React from 'react'
interface AppPropsTypes {
name?: string
age?: number
}
const App: React.FC<AppPropsTypes> = function ({
name = '张三',
age = 18
}) {
return <div>App组件</div>
}
export default App
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 2、事件类型标注
常用的事件类型有
- 鼠标事件:React.MouseEvent
- 键盘事件:React.KeyboardEvent
- 表单事件:React.FormEvent
- 更改事件:React.ChangeEvent
- 焦点事件:React.FocusEvent
- 拖拽事件:React.DragEvent
- UI 事件:React.UIEvent
- 滚动事件:React.UIEvent
import React from 'react';
/*
鼠标事件,
如果是button按钮点击,是React.MouseEvent<HTMLButtonElement>,
如果是div点击,则是React.MouseEvent<HTMLDivElement>
*/
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
console.log(e.currentTarget); // `e.currentTarget` 是 HTMLButtonElement
};
const MyComponent: React.FC = () => {
return <button onClick={handleClick}>Click me</button>;
};
// 键盘事件
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
console.log(e.key); // 可以获取按下的键
};
const MyComponent: React.FC = () => {
return <input onKeyDown={handleKeyDown} />;
};
// 表单事件
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); // 防止表单提交
console.log('Form submitted');
};
const MyComponent: React.FC = () => {
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
};
// 更改事件
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value); // 获取输入框的值
};
const MyComponent: React.FC = () => {
return <input onChange={handleChange} />;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
3、为 ref 元素标注类型
import React, { useEffect, useRef } from 'react';
const MyComponent: React.FC = () => {
const myDivRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (myDivRef.current) {
const height = myDivRef.current.scrollHeight;
// 使用获取到的高度
}
}, []); // 确保useEffect只在组件挂载时执行一次
return (
<div ref={myDivRef}>
<!-- 组件内容 -->
</div>
);
};
export default MyComponent;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
编辑 (opens new window)
上次更新: 7/1/2024, 4:56:33 PM