在 React 中使用 useRef

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>

        </>

    );

};

为什么我的引用没有定义?我需要将代码重构为类吗?


哔哔one
浏览 121回答 1
1回答

摇曳的蔷薇

你违反了 React Hook 规则。钩子应该在顶部的功能组件中声明。在您的情况下,您在本地函数内声明它,并且在该函数之外不可用。它必须是这样的:const App = () => {&nbsp; &nbsp; const randomChar = useRef(null); // <---declare it here&nbsp; &nbsp; function hideCharacter(){&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; randomChar.classList.add('hide');&nbsp; &nbsp; }&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <RandomChar ref={randomChar} /> // error: not defined&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button class="btn btn-primary" onClick={hideCharacter()}>Load another one</button>&nbsp; &nbsp; &nbsp; &nbsp; </>&nbsp; &nbsp; );};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript