September 28, 2022

useState hooki | Hooks qo'llanma 7

React componentlarining statelarini useState bilan boshqarish.

CodeSandbox link

Bu darsdagi to'liq kodni quyidan topa olasiz: https://codesandbox.io/s/react-usestate-fcen58

Komponentingizni yarating

Quyidagicha button komponent yarating.

import React from "react"

const Button = () => {
		return <button>Siz 0 marta bosdingiz</button>;
}

export default Button

Import useState

useState ni ishlatish uchun uni faylning yuqori qismida import qilib olishimiz kerak.

import React, { useState } from "react"

useState hookining anatomiyasi

useState 3 ta qismdan iborat: state variable, stateni yangilash uchun funksiya va boshlang'ich(initial) qiymat. Bu qismlar bilan yaxshiroq tanishish uchun pasdagi rasmga qarang.

State variable ni belgilash

Endi biz buttonni necha marta bosganimizi bilish uchun ishlatadigan state ya'ni count stateni belgilab olamiz. Uning boshlang'ich qiymati 0.

const [count, setCount] = useState(0)

Buttonimizdagi 0 ni count variable bilan almashtiramiz.

<button></button>

Va qachonki button bosilganda statening qiymatini 1ga oshiruvchi funksiyani ham yozishimiz kerak.

<button onClick={() => setCount(count + 1)}>Siz {count} marta bosdingiz</button>; 

Stylelar bilan yakuniy kod

Komponentimizga styled-components orqali style beramiz.

import React, { useState } from "react";
import styled from "styled-components";

const MyButton = () => {
    const [count, setCount] = useState(0);

    return (
        <Button onClick={() => setCount(count + 1)}>
           Siz {count} marta bosdingiz
        </Button> 
    );
};

export default MyButton;

const Button = styled.button`
    background: linear-gradient(91.4deg, #2fb8ff 0%, #9eecd9 100%);
    padding: 12px 25px;
    border: none;
    border-radius: 30px;
    color: white;
    font-weight: bold;
    font-family: Segoe UI, sans-serif;
`;

Yana ham ko'proq ma'lumotga ega bo'lishni istasangiz bu doc bilan tanishib chiqing.