useRef hooki | Hooks qo'llanma 9
JavaScriptdagi getElementById ni o'rnini bosuvchi useRef hooki.
useRef Vanilla JavaScriptdagi getElementById, getElementByClassName yoki querySelectors larni o'rnini bosuvchi ko'p ishlatiladigan hooklardan biri. Boshqa so'z bilan aytganda, dasturingizdagi elementni belgilab olish va uni qachon hohlasangiz chaqirish imkonini beradi. Bu bo'limda useRefni qanday ishlatishni o'rganamiz.
CodeSandbox link
Bu darsdagi to'liq kodni quyidan topa olasiz: https://codesandbox.io/s/react-useref-tvebmc
Componentingiz yarating
Button va Inputdan iborat componentni yaratamiz va button bosilganda, inputdagi qiymat/value xabar(alert) sifatida chiqadi.
import React from "react"; const MyButton = () => { return ( <> <input type="text" /> <button onClick={() => alert("")}> Bosing </button> </> ); }; export default MyButton;
Import hook
Faylning yuqori qismida React kutubxonasidan useRef hookini import qilib olamiz.
import React, { useRef } from "react"
ref yaratish
useRef hooki yordamida ref yartamiz. Qavslar ichida boshlang'ich qiymat beramiz. Odatda bu null yoki undefined bo'ladi.
const ref = useRef(null)
Keyin esa bu refni input elementimizga beramiz.
<input type="text" ref={ref} />
useRef doimo ayni damdagi objectni qaytaradi va haqiqiy HTML elementini olishimiz uchun biz ref.current ni ishga solamiz. Button bosilganda inputning valuesi alert sifatida chiqishini uchun quyidagicha amalga oshiramiz.
<> <input type="text" ref={ref} /> <button onClick={() => alert(ref.current.value)}> Bosing </button> </>
Stylelar bilan yakuniy kod
import React, { useRef} from "react"; import styled from "styled-components"; const MyButton = () => { const ref = useRef(null); return ( <> <input type="text" ref={ref} /> <Button onClick={() => alert(ref.current.value)}> Bosing </Button> </> ); }; export default MyButton; const Button = styled.button` background: linear-gradient(91.4deg, #2fb8ff 0%, #9eecd9 100%); padding: 2px 25px; border: none; border-radius: 30px; color: #fff; font-weight: bold; font-family: Segoe UI, sans-serif; cursor: pointer; :focus { outline: none; } `;