简体   繁体   中英

React JS doesn't render after function is done

const handleMenu = async () => {
        let menu = await document.querySelector('.navbar-list');
        menu.classList.toggle('.navbar-list-active');
    }

return (
    <div className="navbar-list">
                    <div onClick={handleMenu} className="hamburger">
                    </div>
    </div>
)

The thing is that after class is added to component it really added on the element, but the CSS styling doesn't appear on the element with added class, is this something React is doing? How can I force CSS to re-render the page?

await doesn't do anything useful unless the value you are awaiting is a promise . querySelector returns either null or an element: never a promise. Your code won't wait for the element to exist .

Now, you can use useRef to get a reference to the element which would then let you toggle the class on it… but don't.

The React way to solve this problem is to store the toggled state in the state and deal with it in the JSX.

const MyComponent = () => {

    const [active, setActive] = useState(false);

    const classNames = ["navbar-list"];
    if (active) classNames.push("navbar-list-active"); 

    const handleMenu = () => setActive(!active);

    return (
        <div className={classNames}>
            <button onClick={handleMenu} className="hamburger">
                Toggle Menu
            </button>
        </div>
    ;)
}

Note that I've changed the div to a button. This is an important accessibility feature and allows the menu to be activated by people who don't use a pointing device to access a page. There is more you should do for accessibility and this article is a good starting point (although it uses traditional DOM instead of React so you'll need to adapt it to use state as I did here).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM