Komponen Kelas Bereaksi


Sebelum React 16.8, komponen Class adalah satu-satunya cara untuk melacak status dan siklus hidup pada komponen React. Komponen fungsi dianggap "tanpa status".

Dengan penambahan Hooks, komponen Function sekarang hampir setara dengan komponen Class. Perbedaannya sangat kecil sehingga Anda mungkin tidak perlu menggunakan komponen Kelas di React.

Meskipun komponen Fungsi lebih disukai, tidak ada rencana saat ini untuk menghapus komponen Kelas dari Bereaksi.

Bagian ini akan memberi Anda gambaran umum tentang cara menggunakan komponen Kelas di React.

Jangan ragu untuk melewati bagian ini, dan gunakan Komponen Fungsi sebagai gantinya.


Komponen Bereaksi

Komponen adalah bit kode yang independen dan dapat digunakan kembali. Mereka melayani tujuan yang sama seperti fungsi JavaScript, tetapi bekerja secara terpisah dan mengembalikan HTML melalui fungsi render().

Komponen datang dalam dua jenis, komponen Kelas dan komponen Fungsi, dalam bab ini Anda akan belajar tentang komponen Kelas.


Buat Komponen Kelas

Saat membuat komponen React, nama komponen harus dimulai dengan huruf besar.

Komponen harus menyertakan extends React.Componentpernyataan, pernyataan ini membuat pewarisan ke React.Component, dan memberikan komponen Anda akses ke fungsi React.Component.

Komponen juga memerlukan render()metode, metode ini mengembalikan HTML.

Contoh

Buat komponen Kelas yang disebut Car

class Car extends React.Component {
  render() {
    return <h2>Hi, I am a Car!</h2>;
  }
}

Sekarang aplikasi React Anda memiliki komponen bernama Car, yang mengembalikan sebuah <h2>elemen.

Untuk menggunakan komponen ini dalam aplikasi Anda, gunakan sintaks yang sama seperti HTML biasa: <Car />

Contoh

Tampilkan Carkomponen di elemen "root":

ReactDOM.render(<Car />, document.getElementById('root'));


w3schools CERTIFIED . 2022

Dapatkan Sertifikasi!

Selesaikan modul React, kerjakan latihannya, ikuti ujiannya, dan dapatkan sertifikasi w3schools!!

$95 DAFTAR

Konstruktor Komponen

Jika ada constructor()fungsi di komponen Anda, fungsi ini akan dipanggil saat komponen dimulai.

Fungsi konstruktor adalah tempat Anda memulai properti komponen.

Di React, properti komponen harus disimpan dalam objek bernama state.

Anda akan mempelajari lebih lanjut statenanti dalam tutorial ini.

Fungsi konstruktor juga tempat Anda menghormati pewarisan komponen induk dengan menyertakan super() pernyataan, yang mengeksekusi fungsi konstruktor komponen induk, dan komponen Anda memiliki akses ke semua fungsi komponen induk ( React.Component).

Contoh

Buat fungsi konstruktor di komponen Mobil, dan tambahkan properti warna:

class Car extends React.Component {
  constructor() {
    super();
    this.state = {color: "red"};
  }
  render() {
    return <h2>I am a Car!</h2>;
  }
}

Gunakan properti warna dalam fungsi render() :

Contoh

class Car extends React.Component {
  constructor() {
    super();
    this.state = {color: "red"};
  }
  render() {
    return <h2>I am a {this.state.color} Car!</h2>;
  }
}


Atribut

Cara lain untuk menangani properti komponen adalah dengan menggunakan props.

Alat peraga seperti argumen fungsi, dan Anda mengirimkannya ke dalam komponen sebagai atribut.

Anda akan belajar lebih banyak tentang propsdi bab berikutnya.

Contoh

Gunakan atribut untuk meneruskan warna ke komponen Mobil, dan gunakan dalam fungsi render():

class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.color} Car!</h2>;
  }
}

ReactDOM.render(<Car color="red"/>, document.getElementById('root'));


Alat Peraga di Konstruktor

Jika komponen Anda memiliki fungsi konstruktor, props harus selalu diteruskan ke konstruktor dan juga ke React.Component melalui super()metode.

Contoh

class Car extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h2>I am a {this.props.model}!</h2>;
  }
}

ReactDOM.render(<Car model="Mustang"/>, document.getElementById('root'));


Komponen dalam Komponen

Kita dapat merujuk ke komponen di dalam komponen lain:

Contoh

Gunakan komponen Mobil di dalam komponen Garasi:

class Car extends React.Component {
  render() {
    return <h2>I am a Car!</h2>;
  }
}

class Garage extends React.Component {
  render() {
    return (
      <div>
      <h1>Who lives in my Garage?</h1>
      <Car />
      </div>
    );
  }
}

ReactDOM.render(<Garage />, document.getElementById('root'));


Komponen dalam File

React adalah tentang menggunakan kembali kode, dan mungkin pintar untuk memasukkan beberapa komponen Anda ke dalam file terpisah.

Untuk melakukannya, buat file baru dengan .js ekstensi file dan masukkan kode di dalamnya:

Perhatikan bahwa file harus dimulai dengan mengimpor React (seperti sebelumnya), dan harus diakhiri dengan pernyataan export default Car;.

Contoh

Ini adalah file baru, kami menamainya Car.js:

import React from 'react';

class Car extends React.Component {
  render() {
    return <h2>Hi, I am a Car!</h2>;
  }
}

export default Car;

Untuk dapat menggunakan Carkomponen, Anda harus mengimpor file di aplikasi Anda.

Contoh

Sekarang kita mengimpor Car.jsfile dalam aplikasi, dan kita dapat menggunakan Car komponen seolah-olah dibuat di sini.

import React from 'react';
import ReactDOM from 'react-dom';
import Car from './Car.js';

ReactDOM.render(<Car />, document.getElementById('root'));


Status Komponen Kelas Bereaksi

Komponen React Class memiliki stateobjek bawaan.

Anda mungkin telah memperhatikan bahwa kami menggunakan statesebelumnya di bagian konstruktor komponen.

Objek stateadalah tempat Anda menyimpan nilai properti milik komponen.

Saat stateobjek berubah, komponen dirender ulang.


Membuat Obyek status

Objek negara diinisialisasi dalam konstruktor:

Contoh

Tentukan stateobjek dalam metode konstruktor:

class Car extends React.Component {
  constructor(props) {
    super(props);
  this.state = {brand: "Ford"};
  }
  render() {
    return (
      <div>
        <h1>My Car</h1>
      </div>
    );
  }
}

Objek negara dapat berisi properti sebanyak yang Anda suka:

Contoh

Tentukan semua properti yang dibutuhkan komponen Anda:

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  render() {
    return (
      <div>
        <h1>My Car</h1>
      </div>
    );
  }
}

Menggunakan stateObjek

Lihat stateobjek di mana saja di komponen dengan menggunakan sintaks:this.state.propertyname

Contoh:

Lihat stateobjek dalam render()metode:

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
      </div>
    );
  }
}


Mengubah stateObjek

Untuk mengubah nilai dalam objek status, gunakan this.setState()metode.

Ketika nilai dalam stateobjek berubah, komponen akan dirender ulang, artinya output akan berubah sesuai dengan nilai baru.

Contoh:

Tambahkan tombol dengan onClickacara yang akan mengubah properti warna:

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  changeColor = () => {
    this.setState({color: "blue"});
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
        <button
          type="button"
          onClick={this.changeColor}
        >Change color</button>
      </div>
    );
  }
}

Selalu gunakan setState()metode untuk mengubah objek status, ini akan memastikan bahwa komponen mengetahui bahwa itu telah diperbarui dan memanggil metode render() (dan semua metode siklus hidup lainnya).


Siklus Hidup Komponen

Setiap komponen dalam React memiliki siklus hidup yang dapat Anda pantau dan manipulasi selama tiga fase utamanya.

Tiga fase tersebut adalah: Mounting , Update , dan Unmounting .


pemasangan

Mounting berarti memasukkan elemen ke dalam DOM.

React memiliki empat metode bawaan yang dipanggil, dalam urutan ini, saat memasang komponen:

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

Metode render()ini diperlukan dan akan selalu dipanggil, yang lain opsional dan akan dipanggil jika Anda mendefinisikannya.


constructor

Metode constructor()dipanggil sebelum yang lain, ketika komponen dimulai, dan ini adalah tempat alami untuk menyiapkan nilai awal statedan nilai awal lainnya.

Metode constructor()ini dipanggil dengan props, sebagai argumen, dan Anda harus selalu memulai dengan memanggil super(props)sebelum yang lain, ini akan memulai metode konstruktor induk dan memungkinkan komponen untuk mewarisi metode dari induknya ( React.Component).

Contoh:

Metode constructorini dipanggil, oleh React, setiap kali Anda membuat komponen:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


getDerivedStateFromProps

Metode getDerivedStateFromProps()ini dipanggil tepat sebelum merender elemen di DOM.

Ini adalah tempat alami untuk mengatur stateobjek berdasarkan inisial props.

It takes state as an argument, and returns an object with changes to the state.

The example below starts with the favorite color being "red", but the getDerivedStateFromProps() method updates the favorite color based on the favcol attribute:

Example:

The getDerivedStateFromProps method is called right before the render method:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritecolor: props.favcol };
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));


render

The render() method is required, and is the method that actually outputs the HTML to the DOM.

Example:

A simple component with a simple render() method:

class Header extends React.Component {
  render() {
    return (
      <h1>This is the content of the Header component</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


componentDidMount

The componentDidMount() method is called after the component is rendered.

This is where you run statements that requires that the component is already placed in the DOM.

Example:

At first my favorite color is red, but give me a second, and it is yellow instead:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


Updating

The next phase in the lifecycle is when a component is updated.

A component is updated whenever there is a change in the component's state or props.

React has five built-in methods that gets called, in this order, when a component is updated:

  1. getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render()
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()

The render() method is required and will always be called, the others are optional and will be called if you define them.


getDerivedStateFromProps

Also at updates the getDerivedStateFromProps method is called. This is the first method that is called when a component gets updated.

This is still the natural place to set the state object based on the initial props.

The example below has a button that changes the favorite color to blue, but since the getDerivedStateFromProps() method is called, which updates the state with the color from the favcol attribute, the favorite color is still rendered as yellow:

Example:

If the component gets updated, the getDerivedStateFromProps() method is called:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritecolor: props.favcol };
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));


shouldComponentUpdate

In the shouldComponentUpdate() method you can return a Boolean value that specifies whether React should continue with the rendering or not.

The default value is true.

The example below shows what happens when the shouldComponentUpdate() method returns false:

Example:

Stop the component from rendering at any update:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  shouldComponentUpdate() {
    return false;
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));

Example:

Same example as above, but this time the shouldComponentUpdate() method returns true instead:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  shouldComponentUpdate() {
    return true;
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


render

The render() method is of course called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes.

The example below has a button that changes the favorite color to blue:

Example:

Click the button to make a change in the component's state:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


getSnapshotBeforeUpdate

In the getSnapshotBeforeUpdate() method you have access to the props and state before the update, meaning that even after the update, you can check what the values were before the update.

If the getSnapshotBeforeUpdate() method is present, you should also include the componentDidUpdate() method, otherwise you will get an error.

The example below might seem complicated, but all it does is this:

When the component is mounting it is rendered with the favorite color "red".

When the component has been mounted, a timer changes the state, and after one second, the favorite color becomes "yellow".

This action triggers the update phase, and since this component has a getSnapshotBeforeUpdate() method, this method is executed, and writes a message to the empty DIV1 element.

Then the componentDidUpdate() method is executed and writes a message in the empty DIV2 element:

 

Example:

Use the getSnapshotBeforeUpdate() method to find out what the state object looked like before the update:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    document.getElementById("div1").innerHTML =
    "Before the update, the favorite was " + prevState.favoritecolor;
  }
  componentDidUpdate() {
    document.getElementById("div2").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }
  render() {
    return (
      <div>
        <h1>My Favorite Color is {this.state.favoritecolor}</h1>
        <div id="div1"></div>
        <div id="div2"></div>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


componentDidUpdate

The componentDidUpdate method is called after the component is updated in the DOM.

The example below might seem complicated, but all it does is this:

When the component is mounting it is rendered with the favorite color "red".

When the component has been mounted, a timer changes the state, and the color becomes "yellow".

This action triggers the update phase, and since this component has a componentDidUpdate method, this method is executed and writes a message in the empty DIV element:

Example:

The componentDidUpdate method is called after the update has been rendered in the DOM:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  componentDidUpdate() {
    document.getElementById("mydiv").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <div id="mydiv"></div>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


Unmounting

The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it.

React has only one built-in method that gets called when a component is unmounted:

  • componentWillUnmount()

componentWillUnmount

The componentWillUnmount method is called when the component is about to be removed from the DOM.

Example:

Click the button to delete the header:

class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = {show: true};
  }
  delHeader = () => {
    this.setState({show: false});
  }
  render() {
    let myheader;
    if (this.state.show) {
      myheader = <Child />;
    };
    return (
      <div>
      {myheader}
      <button type="button" onClick={this.delHeader}>Delete Header</button>
      </div>
    );
  }
}

class Child extends React.Component {
  componentWillUnmount() {
    alert("The component named Header is about to be unmounted.");
  }
  render() {
    return (
      <h1>Hello World!</h1>
    );
  }
}

ReactDOM.render(<Container />, document.getElementById('root'));