简体   繁体   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>
        </>
    );
};

Why my ref is not defined?为什么我的 ref 没有定义? I need to refactor code to class?我需要重构代码来上课吗?

You are breaking the React Hook Rules.你违反了 React Hook 规则。 Hooks should be declared in the functional component at top.钩子应该在顶部的功能组件中声明。

In your case you are declaring it inside a local function and it is not available outside that.在您的情况下,您是在本地函数中声明它,并且在该函数之外不可用。

It has to be like:它必须是这样的:

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