嗶嗶one
2023-07-14 10:26:46
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> </> );};為什么我的引用沒有定義?我需要將代碼重構(gòu)為類嗎?
1 回答

搖曳的薔薇
TA貢獻(xiàn)1793條經(jīng)驗(yàn) 獲得超6個(gè)贊
你違反了 React Hook 規(guī)則。鉤子應(yīng)該在頂部的功能組件中聲明。
在您的情況下,您在本地函數(shù)內(nèi)聲明它,并且在該函數(shù)之外不可用。
它必須是這樣的:
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>
</>
);
};
添加回答
舉報(bào)
0/150
提交
取消