[英]“Toggle undifined” message when click button in React.js
I am newbie in React js, and I have made a toggle class button in Reactjs.我是 React js 的新手,我在 Reactjs 中制作了一个切换 class 按钮。
But When I clicked i got error message.但是当我单击时,我收到了错误消息。
TypeError: Cannot read property 'toggle' of undefined TypeError:无法读取未定义的属性“切换”
This is my code below.这是我下面的代码。 What is wrong with my code?我的代码有什么问题? please help.请帮忙。
import React from 'react'
export default function About() {
const navRef = React.useRef(null);
const btnRef = React.useRef(null);
const onToggleClick = () => {
navRef.current.classList.toggle("show");
btnRef.current.classList.toggle("active");
};
return (
<>
<button onClick={onToggleClick} ref={btnRef}>Toggle</button>
<nav ref={navRef}>Navigation menu</nav>
</>
);
}
In react, you can learn to toggle by using state.在反应中,您可以学习使用 state 进行切换。
In the following example, we set a toggle state show
, and toggle it true/false
.在下面的示例中,我们设置了一个切换 state show
,并切换它true/false
。
We will then set the className with the appropriate css class we want it to have.然后,我们将使用适当的 css class 设置 className。
import React, { useState, useEffect } from 'react'
export default function About() {
const [ show, setShow ] = useState(false) //default to hide
useEffect(() => {
if (show) {
document.body.classList.add('bodyclass');
} else {
document.body.classList.remove('bodyclass');
}
}, [show])
const onToggleClick = () => setShow(!show) //if it's true, set to false. vice-versa
return (
<>
<button onClick={onToggleClick} className={ show ? 'active' : ''}>Toggle</button>
<nav className={ show ? 'show' : ''}>Navigation menu</nav>
</>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.