使用Hoc(高阶组件)和Context
import React, { createContext, useContext } from "react";
const NavContext = createContext(null);
const histroy = window.history;
export default function FuncComRouter() {
return (
<NavContext.Provider value={histroy}>
<ChildRouter />
</NavContext.Provider>
);
}
const withRouter = (Component) => {
return function WithRouterComponent() {
const histroy = useContext(NavContext);
return <Component histroy={histroy} />;
};
};
const Child = ({ histroy }) => {
return (
<div>
<button onClick={() => histroy.pushState({}, undefined, "/hello")}>
Go to hello
</button>
</div>
);
};
const ChildRouter = withRouter(Child);