何がUserefフック反応ですか?


useref hookについての私の新しいポストは、ここにあります.

Userefとは
対応するドキュメントに従って、userEFフックは現在のプロパティが渡された引数(初期値)に初期化されるmutable refオブジェクトを返します.返されるオブジェクトは、コンポーネントの完全な生存期間を保持します.
ドキュメントで定義された定義を打破すると、三つのことがあります.
  • は、可変オブジェクト
  • を返します
  • 現在のプロパティ(初期化する必要がある)
  • を持っています
  • 返されたオブジェクトは、コンポーネント
  • の寿命の間持続します
    文法
    const refVariable = useRef(null)
    
    // refVariable = Object which has the current property. So we have access to refVariable.current
    
    // Initial value of refVariable.current
    

    userefフックを使うとき?
    useref hokの2つの主な使用例は以下の通りです:
    DOMノードにアクセスする

  • 可変可変
  • を維持している

  • userefは変更可能な変数を保つという点でusestateに似ています.大きな違いは、コンポーネントの再レンダリングをトリガーしないことです.
    いくつかの例.
    最も一般的なuserefの1つは、入力要素にフォーカスをもたらすことです.
    import React, {useRef, useEffect} from 'react'
    
    const App () => {
        const firstNameRef = useRef(null) //intialize the current property to nul
    
        useEffect(() => {
            firstNameRef.current.focus() //set focus on firstNameRef
        }, [])
    
        return (
            <>
              {/*Use the "ref" attribute to set the input DOM node equal to "firstNameRef" */}
              <input type={text} ref={firstNameRef} placeholder="First Name Here..." />
              <input type={text} placeholder="Last Name here..." />
              <button>Submit</button>
              </>
        )
    }
    
    したがって、userefはドキュメントを使用するのと類似しています.QuerySelectorまたはドキュメント.GetElementByid
    const divElement = document.querySelector(".sample")
    
    <div className="sample" ref={divRed}>Sample Div</div>
    
    //where divRef is already defined by useRef
    
    別の例を挙げましょう.コンポーネントのレンダリング回数を表示したい場合を想定します.状態を使用してこれを実行しようとすると、無限ループの状態になります(コンポーネントのレンダラが別のレンディングをトリガーしたときにカウンタ状態をインクリメントするため、永遠に続く).これはuserefで解決できます.
    import React, {useRef, useEffect, useState} from 'react'
    
    const App = () => {
        //initialize the current property of renderCount 1
        const renderCount = useRed(1)
    
        useEffect(() => {
            renderCount.current++; 
            //increment renderCount.current everytime the component renders
        })
    
        return (
            <>
              <input
              type={text}
              onChange={e => setName(e.target.walue)}
              placeholder="First name here..."
              />
              <p>This component rendered {renderCount.current} times </p>
              </>
        )
    }
    
    それで、あなたがあなたの構成要素に状態を追加したいなら、レンダラの上で持続して、更新されるとき、再表示を引き起こすことができるならば、USENTかUsereducerに行ってください.
    あなたのコンポーネントにステートを追加したい場合は、レンダラを継続しますが、更新時に再描画をトリガーしません.
    💻 ハッピーコーディングを読んでくれてありがとう🥂