我想这样做。怎么做。为文档体添加应用上下文提供程序。但不应影响现有内容。
ReactDOM.createRoot(document.body).render( <AppContextProvider> {document.body} </AppContextProvider> );
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> );
1条答案
按热度按时间eqqqjvef1#
首先需要构造appContextProvider函数,如下所示
然后在导入应用组件后将其与函数 Package 在一起