import React, { useState, useEffect, createContext } from 'react';
const RouterContext = createContext();
function Link({ to, children }) {
return (
<RouterContext.Consumer>
{({ history }) => (
// 创建一个 a 标签,设置 href 为传入的 to 属性
<a
href={to}
// 设置点击事件,在点击时阻止默认的跳转行为
onClick={(e) => {
e.preventDefault();
// 使用历史对象的 push 方法进行页面跳转
history.push(to);
}}
>
// 将 children 属性渲染为 a 标签的子元素
{children}
</a>
)}
</RouterContext.Consumer>
);
}
function Route({ path, component: Component }) {
return (
<RouterContext.Consumer>
{({ currentPath }) => (currentPath === path ? <Component /> : null)}
</RouterContext.Consumer>
);
}
function BrowserRouter({ children }) {
const [currentPath, setCurrentPath] = useState(window.location.pathname);
useEffect(() => {
const handlePopstate = () => {
setCurrentPath(window.location.pathname);
};
window.addEventListener('popstate', handlePopstate);
return () => {
window.removeEventListener('popstate', handlePopstate);
};
}, []);
const history = {
push: (path) => {
window.history.pushState({}, '', path);
setCurrentPath(path);
},
};
return (
<RouterContext.Provider value={{ history, currentPath }}>
{children}
</RouterContext.Provider>
);
}
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/home">Home</Link>
<Link to="/about">About</Link>
</nav>
<main>
<Route path="/home" component={Home} />
<Route path="/about" component={About} />
</main>
</BrowserRouter>
);
}
function Home() {
return <h2>Home Page</h2>;
}
function About() {
return <h2>About Page</h2>;
}
export default App;