簡體   English   中英

在 React 中使用 useRef

[英]Using useRef in React

const App = () => {
    function hideCharacter(){
        const randomChar = useRef(null);
        randomChar.classList.add('hide');
    }
    return (
        <> 
            <RandomChar ref={randomChar} /> // error: not defined
            <button class="btn btn-primary" onClick={hideCharacter()}>Load another one</button>
        </>
    );
};

為什么我的 ref 沒有定義? 我需要重構代碼來上課嗎?

你違反了 React Hook 規則。 鈎子應該在頂部的功能組件中聲明。

在您的情況下,您是在本地函數中聲明它,並且在該函數之外不可用。

它必須是這樣的:

const App = () => {
    const randomChar = useRef(null); // <---declare it here
    function hideCharacter(){        
        randomChar.classList.add('hide');
    }
    return (
        <> 
            <RandomChar ref={randomChar} /> // error: not defined
            <button class="btn btn-primary" onClick={hideCharacter()}>Load another one</button>
        </>
    );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM