React.FC
Description is not a regular function, but a functional component. There must be a return value.
1
2
3const TodoList: React.FC = () => {
return <div></div>
};
Props
There are two ways to write props types, and they are equivalent.
Generic interface
React.FC<props type>
1
2
3
4
5
6interface TodoListProps {
items: {id: string, text: string}[];
};
const TodoList: React.FC<TodoListProps> = props => {
return(...)
}
Declare the props type in the parameters
1
2
3
4
5
6interface TodoListProps {
items: {id: string, text: string}[];
};
const TodoList = (props: TodoListProps) => {
return(...)
}
props may also be functions. This should be written as:
1
2
3
4
5
6type NewTodoProps = {
onAddTodo: (todoText: string) => void;
}
const NewTodo: React.FC<NewTodoProps> = props => {
return(...)
}
Type of event
Common Event event objects are as follows:
Clipboard event object: ClipboardEvent<T = Element>
Drag event object: DragEvent<T = Element>
Focus event object: FocusEvent<T = Element>
Form event object: FormEvent<T = Element>
Change event object: ChangeEvent<T = Element>
Keyboard event object: KeyboardEvent<T = Element>
Mouse event object: MouseEvent<T = Element, E = NativeMouseEvent>
Touch event object: TouchEvent<T = Element>
Wheel event object: WheelEvent<T = Element>
Animation event object: AnimationEvent<T = Element>
Transition event object: TransitionEvent<T = Element>
The generic types of these Event event objects will receive an Element element type, which is the type of the label element bound to this event.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17type State = {
text: string;
};
const App: React.FC = () => {
const [text, setText] = useState<string>("")
const onChange = (e: React.FormEvent<HTMLInputElement>): void => {
setText(e.currentTarget.value);
};
return (
<div>
<input type="text" value={text} onChange={onChange} />
</div>
);
}
useState() declaration type
Use useState
() to declare the type of state. By default, React will automatically deduce the type of state and update function based on the initial value of the set state. If the initial value is null, the type of state needs to be explicitly declared.
1
2
3const [count, setCount] = useState<number>(1); //<number> can be omitted
const [count, setCount] = useState<number | null>(null); //need to display statement
const [todos, setTodos] = useState<{id: string; text: string}[]>([]); //It is best to change it to interface[].If state is an object and you want to initialize an empty object, you can use assertions to handle it:
1
const [user, setUser] = React.useState<IUser>({} as IUser);
Use useRef to get the type of user input
1
const textInputRef = useRef<HTMLInputElement>(null);
More knowledge about using TS in React
https://juejin.cn/post/7021674818621669389