reactjs 如何在react中为文档体添加AppContext Provider?

6za6bjd0  于 2023-04-20  发布在  React
关注(0)|答案(1)|浏览(106)

我想这样做。怎么做。为文档体添加应用上下文提供程序。但不应影响现有内容。

ReactDOM.createRoot(document.body).render(
<AppContextProvider>
  {document.body}
</AppContextProvider>
);
eqqqjvef

eqqqjvef1#

首先需要构造appContextProvider函数,如下所示

import { useReducer, createContext, useMemo } from 'react';
import { initialState, contextReducer } from 'yourOwnReducer';

const AppContext = createContext();

function AppContextProvider({ children }) { 
const [state, dispatch] = useReducer(contextReducer, initialState);
const value = useMemo(() => [state, dispatch], [state]);

return <AppContext.Provider value={value}>{children} 
</AppContext.Provider>;
}

export default AppContextProvider;

然后在导入应用组件后将其与函数 Package 在一起

import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { createRoot } from "react-dom/client";

import App from "./app";

import AppContextProvider from "./AppContextProvider";

const root = createRoot(document.getElementById("root"));

root.render(
  <React.StrictMode>
   <BrowserRouter>
    <AppContextProvider>
     <Routes>
      <Route path="/*" element={<App />} />
     </Routes>
    </AppContextProvider>
  </BrowserRouter>
 </React.StrictMode>
);

相关问题