React bilan TypeScript
Props va children'ni tiplash, hodisalar, useState, useRef, useReducer, generic komponentlar va ComponentProps.
Bu nima?
React loyihalarining aksariyati TypeScript'da yoziladi. Turlar props xatolarini kompilyatsiyada ushlaydi va komponentlardan foydalanishda avtoto'ldirish beradi. React bo'limi asoslarini bilgan holda o'qing.
Props
type ButtonProps = {
label: string;
variant?: 'primary' | 'secondary';
disabled?: boolean;
onClick: () => void;
};
function Button({ label, variant = 'primary', disabled = false, onClick }: ButtonProps) {
return <button className={variant} disabled={disabled} onClick={onClick}>{label}</button>;
}children
import type { ReactNode } from 'react';
type CardProps = {
title: string;
children: ReactNode; // JSX, matn, raqam, null, massiv — hammasi
};
function Card({ title, children }: CardProps) {
return <section><h2>{title}</h2>{children}</section>;
}React.FC ishlatish shart emas: oddiy funksiya va props turi yetarli va tushunarliroq.
Hodisalar
function SearchForm() {
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
<input onChange={handleChange} />
</form>
);
}Turni eslab qolish qiyin bo'lsa, handler'ni JSX ichida inline yozib, sichqonchani ustiga olib boring: editor turni ko'rsatadi.
Hooklar
const [count, setCount] = useState(0); // number — o'zi chiqaradi
const [user, setUser] = useState<User | null>(null); // boshlang'ich null bo'lsa, turni ko'rsating
const [items, setItems] = useState<string[]>([]); // bo'sh massiv — never[] bo'lmasligi uchun
const inputRef = useRef<HTMLInputElement>(null); // DOM element uchun
inputRef.current?.focus();
const timerRef = useRef<number | undefined>(undefined); // o'zgaruvchan qiymat uchunuseReducer va discriminated union
type State = { count: number };
type Action =
| { type: 'increment' }
| { type: 'add'; payload: number }
| { type: 'reset' };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'add': return { count: state.count + action.payload }; // payload faqat shu yerda
case 'reset': return { count: 0 };
}
}
const [state, dispatch] = useReducer(reducer, { count: 0 });
dispatch({ type: 'add', payload: 5 });
dispatch({ type: 'add' }); // Xato: payload yo'qGeneric komponentlar
type ListProps<T> = {
items: T[];
renderItem: (item: T) => ReactNode;
getKey: (item: T) => string | number;
};
function List<T>({ items, renderItem, getKey }: ListProps<T>) {
return <ul>{items.map((item) => <li key={getKey(item)}>{renderItem(item)}</li>)}</ul>;
}
<List items={users} getKey={(u) => u.id} renderItem={(u) => u.name} /> // u: UserHTML elementini kengaytirish
import type { ComponentProps } from 'react';
type InputProps = ComponentProps<'input'> & {
label: string;
};
function Input({ label, ...rest }: InputProps) {
return <label>{label}<input {...rest} /></label>;
}
<Input label="Email" type="email" placeholder="..." required />Boshqa komponentning props turini olish: ComponentProps<typeof Button>.
Intervyu savollari
ReactNode bilan: u JSX elementlari, matn, raqam, null, undefined va ularning massivlarini qamrab oladi. Faqat bitta JSX element kerak bo'lsa, ReactElement ishlatiladi.
Boshlang'ich qiymatdan to'g'ri tur chiqmasa: useState(null) faqat null turini beradi, shuning uchun useState<User | null>(null) yoziladi. Bo'sh massivda ham useState<string[]>([]) kerak. Oddiy useState(0) uchun shart emas.
DOM uchun useRef<HTMLInputElement>(null): current ni React boshqaradi. O'zgaruvchan qiymat (timer id, oldingi qiymat) uchun useRef<number | undefined>(undefined): current ni o'zingiz o'zgartirasiz.
Shart emas va ko'pchilik undan voz kechgan. Props turini to'g'ridan-to'g'ri parametrga yozish soddaroq, generic komponentlar bilan yaxshi ishlaydi va default qiymatlar bilan muammo bermaydi. React 18 dan beri FC endi children ni avtomatik qo'shmaydi.
ComponentProps<'input'> (yoki ref kerak bo'lmasa ComponentPropsWithoutRef<'input'>) ni o'z props'lar bilan & orqali birlashtirib, qolganlarini ...rest bilan input ga uzatish. Nomi to'qnashadigan props'lar bo'lsa, avval ularni Omit bilan olib tashlash kerak.