gpt4 book ai didi

javascript - 来自单独应用程序的 react 组件未集成到主应用程序中

转载 作者:行者123 更新时间:2023-12-03 16:09:52 25 4
gpt4 key购买 nike

我是 React 的新手,我正在尽最大努力将一个应用程序放在一起,所以我创建了两个主要部分,我想将它们组合起来,但我不确定如何去做吧。
这里是 错误 我越来越:TypeError: Cannot read property 'openSidebar' of undefined指向 这个组件:

// Sidebar button and opening of sidebar
// main function created to open sidebar button
import React from 'react';
import { FaBars } from 'react-icons/fa';
import { useGlobalContext } from './context';

const Home = () => { /*const data can setup data form each button under sidebar */ //<----- ERROR HERE
const { openSidebar } = useGlobalContext();
return (
<main>
<button onClick={openSidebar} className='sidebar-toggle'>
<FaBars />
</button>
</main>
);
};

export default Home;
我已经以多种方式搜索了错误,但它们似乎都特定于它们发生的应用程序。
感谢您提供任何帮助。
如果需要更多信息,请告诉我!
编辑:
下面是处理 const 的组件 opendSidebar
// context class need to be added without change,
// setting of close open sidebar
import React, { useState, useContext } from 'react';

const AppContext = React.createContext(undefined, undefined);

const AppProvider = ({ children }) => {
const [isSidebarOpen, setIsSidebarOpen] = useState(false);

const openSidebar = () => {
setIsSidebarOpen(true);
};
const closeSidebar = () => {
setIsSidebarOpen(false);
};


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

export const useGlobalContext = () => {
return useContext(AppContext);
};

export { AppContext, AppProvider };

最佳答案

正如我在评论中提到的,您似乎缺少 <AppProvider /> .这提供了 context对所有感兴趣的 child 的值(value)观进一步下降。如果找不到上下文提供程序 defaultValue提供给 createContext (在您的情况下未定义)将被使用。
请看this例子。特别是根 App.js .你会看到一个类似的结构

<AppProvider>
<Home />
<AppProvider />
那真的是唯一缺少的东西。

关于javascript - 来自单独应用程序的 react 组件未集成到主应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64976791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com