Utilizziamo i cookie per migliorare la tua esperienza sul sito
CodeWorlds

Typowanie Komponentow Funkcyjnych

W React każdy komponent to funkcja. TypeScript pozwala nam precyzyjnie określić, co ta funkcja przyjmuje (props) i co zwraca (JSX). To jak instrukcja obsługi każdego modułu na statku kosmicznym.

React.FC vs jawne typowanie

Istnieja dwa popularne sposoby typowania komponentów funkcyjnych w React:

Sposób 1: React.FC (Function Component)

1import React from 'react';
2
3// React.FC automatycznie dodaje typ children i zwracany typ
4const StarInfo: React.FC = () => {
5  return <p>Informacje o gwiezdzie</p>;
6};
7
8// React.FC z propsami
9interface StarProps {
10  name: string;
11  brightness: number;
12}
13
14const StarCard: React.FC<StarProps> = ({ name, brightness }) => {
15  return (
16    <div>
17      <h3>{name}</h3>
18      <p>Jasnosc: {brightness}</p>
19    </div>
20  );
21};

Sposób 2: Jawne typowanie (zalecane)

1// Jawne typowanie - bardziej przejrzyste i elastyczne
2interface StarProps {
3  name: string;
4  brightness: number;
5}
6
7function StarCard({ name, brightness }: StarProps): JSX.Element {
8  return (
9    <div>
10      <h3>{name}</h3>
11      <p>Jasnosc: {brightness}</p>
12    </div>
13  );
14}
15
16// Lub jako arrow function
17const StarCardArrow = ({ name, brightness }: StarProps): JSX.Element => {
18  return (
19    <div>
20      <h3>{name}</h3>
21      <p>Jasnosc: {brightness}</p>
22    </div>
23  );
24};

Dlaczego jawne typowanie jest zalecane?

Spolecznosc React odchodzi od React.FC z kilku powodow:

  1. React.FC domyslnie dodaje children - nawet gdy komponent ich nie uzywa
  2. Jawne typowanie jest bardziej czytelne - widac dokładnie co komponent przyjmuje
  3. Lepsza kompatybilnosc - działa identycznie z function i arrow function
1// React.FC - children jest zawsze dostępne (nawet jeśli niepotrzebne)
2const Badge: React.FC<{ label: string }> = ({ label, children }) => {
3  return <span>{label}{children}</span>; // children może byc undefined
4};
5
6// Jawne typowanie - children trzeba jawnie dodac
7interface BadgeProps {
8  label: string;
9}
10
11function Badge({ label }: BadgeProps): JSX.Element {
12  return <span>{label}</span>; // nie ma children, bo nie jest w props
13}

Zwracany typ komponentu

Komponent React może zwracać różne typy:

1// JSX.Element - najczęściej używany
2function Planet(): JSX.Element {
3  return <div>Mars</div>;
4}
5
6// React.ReactElement - bardziej precyzyjny
7function Planet(): React.ReactElement {
8  return <div>Mars</div>;
9}
10
11// React.ReactNode - najbardziej elastyczny (JSX, string, number, null)
12function MaybeContent(): React.ReactNode {
13  return null; // może zwrocic null
14}
15
16// W praktyce najczęściej pomijamy typ zwracany
17// TypeScript sam go wydedukuje
18function Planet() {
19  return <div>Mars</div>; // TypeScript wie, ze to JSX.Element
20}
Vai a CodeWorlds