import { UserProvider, useUser } from "./UserContext";
const LoggedInUser = () => {
const { user } = useUser();
return (
<p style={{ textAlign: "right" }}>
by<span>{user.name}</span>
</p>
);
};
const Header = () => {
return (
<header>
<h2 style={{ textAlign: "center" }}>Blog App</h2>
<LoggedInUser />
</header>
);
};
const Page = () => {
const { user } = useUser();
return (
<div style={{ marginLeft: "20px", marginRight: "30px" }}>
<h2>What is Lorem ipsum</h2>
<p>
Lorem ipsum dolor sit amet, officia excepteur ex fugiat reprehenderit
enim labore culpa sint ad nisi Lorem pariatur mollit ex esse
exercitation amet. Nisi anim cupidatat excepteur officia. Reprehenderit
nostrud nostrud ipsum Lorem est aliquip amet voluptate voluptate dolor
minim nulla est proident. Nostrud officia pariatur ut officia. Sit irure
elit esse ea nulla sunt ex occaecat reprehenderit commodo officia dolor
Lorem duis laboris cupidatat officia voluptate. Culpa proident
adipisicing id nulla nisi laboris ex in Lorem sunt duis officia eiusmod.
Aliqua reprehenderit commodo ex non excepteur duis sunt velit enim.
Voluptate laboris sint cupidatat ullamco ut ea consectetur et est culpa
et culpa duis.
</p>
<p>Written by {user.name}</p>
</div>
);
};
function App() {
return (
<div>
<Header />
<Page />
</div>
);
}
function Root() {
return (
<UserProvider>
<App />
</UserProvider>
);
}
export default Root;
这是我的App.jsx
import { createContext, useContext, useState } from "react";
const UserContext = createContext({});
export const UserProvider = ({ children }) => {
const [user] = useState({
name: "John",
email: "john@example.com",
dob: "01/01/2000",
});
return <UserContext.Provider value={{ user }}></UserContext.Provider>;
};
export const useUser = () => useContext(UserContext);
这是我的UserContext.js
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import Root from "./App";
import { UserProvider } from "./UserContext";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Root />
</React.StrictMode>
);
这是我的index.js
但由于某种原因,网站没有呈现任何内容。就像它只是显示一个空白的白色页面。甚至控制台也没有显示任何错误。有人能解释为什么会发生这种情况吗?我该如何解决这个问题?
2条答案
按热度按时间vu8f3i0k1#
问题出在
UserContext.js
你忘了使用
{children}
ryhaxcpt2#
传递
children
,如:或