DEV Community

Jelena Petkovic
Jelena Petkovic

Posted on

3 2 2 2 2

Funkcionalne i Klasne Komponente u React-u sa TypeScript-om

U React-u sa TypeScript-om možemo koristiti dva glavna pristupa za kreiranje komponenti: funkcionalne i klasne komponente. Oba pristupa omogućuju rad sa props i state, ali koriste nešto drugačije paradigme. TypeScript dodatno pojačava razvojnu sigurnost pružanjem statičkog tipiziranja, što nam omogućuje da precizno definišemo oblik props i state.

U nastavku ćemo pogledati primere različitih komponenti, koristeći interface za definisanje tipova, kako bismo osigurali doslednost i čitljivost koda.


F-1. Funkcionalna komponenta bez props i state

U ovom slučaju, jednostavna funkcionalna komponenta koja ne koristi ni props ni state izgleda ovako:

import React from 'react';

const FunctionalComponent: React.FC = () => {
  return <div>Hello, DEV.to!</div>;
};
Enter fullscreen mode Exit fullscreen mode

Ova komponenta samo prikazuje statički tekst.


F-2. Funkcionalna komponenta sa props

Kada želimo da prosledimo podatke kroz props, koristimo interface kako bismo definisali oblik tih podataka:

import React from 'react';

interface IMyProps {
  name: string;
}

const FunctionalComponentWithProps: React.FC<IMyProps> = ({ name }) => {
  return <div>Hello, {name}!</div>;
};
Enter fullscreen mode Exit fullscreen mode

Ovde IMyProps sadrži name koji se koristi za prikaz personalizovanog pozdrava.


F-3. Funkcionalna komponenta sa state

Kada koristimo state u funkcionalnim komponentama, koristimo React-ov useState hook:

import React, { useState } from 'react';

const FunctionalComponentWithState: React.FC = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Ova komponenta koristi lokalni state za praćenje brojača.


F-4. Funkcionalna komponenta sa props i state

Kombinovanjem props i state možemo imati fleksibilne komponente koje primaju podatke kroz props, a manipulišu stanjem interno:

import React, { useState } from 'react';

interface IMyProps {
  initialCount: number;
}

const FunctionalComponentWithPropsAndState: React.FC<IMyProps> = ({ initialCount }) => {
  const [count, setCount] = useState(initialCount);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Ova komponenta koristi initialCount kao prop, a interni state za dinamičko praćenje brojača.



K-1. Klasna komponenta bez props i state

Klasna komponenta bez props i state u React-u izgleda ovako:

import React from 'react';

class ClassComponent extends React.Component {
  render() {
    return <div>Hello, DEV.to!</div>;
  }
}
Enter fullscreen mode Exit fullscreen mode

Ovo je jednostavna klasna komponenta koja prikazuje statički tekst.


K-2. Klasna komponenta sa props

Kada klasna komponenta prima props, definišemo ih pomoću interface:

import React from 'react';

interface IMyProps {
  name: string;
}

class ClassComponentWithProps extends React.Component<IMyProps> {
  render() {
    return <div>Hello, {this.props.name}!</div>;
  }
}
Enter fullscreen mode Exit fullscreen mode

Kao i kod funkcionalne komponente, ovde koristimo props za prikaz personalizovanih podataka.


K-3. Klasna komponenta sa state

Kod klasnih komponenti sa state, definišemo stanje unutar konstruktora:

  • Prazne zagrade u konstruktoru

Ako ne koristite props, možete jednostavno ostaviti prazne zagrade u konstruktoru:

import React from 'react';

interface IMyState {
  count: number;
}

class ClassComponentWithState extends React.Component<{}, IMyState> {
  constructor() {
    super({});
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>Increase</button>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Eksplicitno navesti {} kao tip za props

Ako želite biti eksplicitni u vezi sa props, možete navesti {} kao tip:

import React from 'react';

interface IMyState {
  count: number;
}

class ClassComponentWithState extends React.Component<{}, IMyState> {
  constructor(props: {}) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>Increase</button>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

-> U oba slučaja, TypeScript i React će ispravno funkcionisati. Ako vaša komponenta ne koristi props, jednostavno možete koristiti prazne zagrade u konstruktoru, ali obavezno prosledite {} u super pozivu kako biste izbegli greške u inicijalizaciji.

Ova komponenta koristi state kako bi pratila promene brojača.


K-4. Klasna komponenta sa props i state

Za klasne komponente koje koriste i props i state, možemo kombinovati oba koncepta:

import React from 'react';

interface IMyProps {
  initialCount: number;
}

interface IMyState {
  count: number;
}

class ClassComponentWithPropsAndState extends React.Component<IMyProps, IMyState> {
  constructor(props: IMyProps) {
    super(props);
    this.state = {
      count: props.initialCount
    };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>Increase</button>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Ova komponenta prima početni brojač kroz props, a dalje manipuliše stanjem interno.


Korišćenje interface u TypeScript-u donosi bolje tipiziranje i lakšu čitljivost koda, pogotovo kada radimo sa složenijim strukturama podataka. Sa ovim osnovnim primerima, imate osnovu za pisanje funkcionalnih i klasnih komponenti sa React-om i TypeScript-om.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series