简体   繁体   中英

onClick doesn't fire event React.js

I'm trying to toggle element by clicking on button, however it doesn't do anything. Also note that code is simplified as I didn't want to copy whole app, I just included parts I thought are important. Here is code:

  1. Navbar.js..Here I try to invoke the function it comes from context.js file where I setup my contextAPI

    import { useGlobalContext } from "./context"; const { openSidebar, openSubmenu, closeSubmenu } = useGlobalContext(); <button className="btn toggle-btn" onClick={openSidebar}>
  2. context.js

     const AppContext = React.createContext(); const AppProvider = ({ children }) => { const [isSidebarOpen, setIsSidebarOpen] = useState(false); const openSidebar = () => { console.log("test") setIsSidebarOpen(true); }; return ( <AppContext.Provider value={(isSidebarOpen, openSidebar, closeSidebar)}> {children} </AppContext.Provider> ); } export const useGlobalContext = () => { return useContext(AppContext); }; export { AppContext, AppProvider };
  3. App.js

     document.addEventListener("click", (e) => { console.log(e); console.log(e.target); });
  4. index.js

     import App from "./App"; import { AppProvider } from "./context"; ReactDOM.render( <React.StrictMode> <AppProvider> <App /> </AppProvider> </React.StrictMode>, document.getElementById("root") );

The event listener from App.js displays correctly event and also event.target which is the button. However I don't get any log to console from context.js where it should log "test", not error, not warning, nothing... onClick is completely ignored.

You will find your answer here

onClick={( )=>{openSidebar( )}}

Okay Ive resolved it, the problem was in parentheses in context.js

here is old code:

return (
 <AppContext.Provider value={(isSidebarOpen,  openSidebar, closeSidebar)}>
     {children}
 </AppContext.Provider>

);

here is new one:

return (
    <AppContext.Provider value={{ isSidebarOpen,  openSidebar, closeSidebar }}>
        {children}
    </AppContext.Provider>
);

I needed to replace () with {}

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