反应路由器定义我自己的链接



所以处理路由器导航的<Link />onClick的实现很简单:

const { history } = this.context.router;
history.push(to);

这是从 github 存储库中提取的

所以在我的应用程序中它应该可以工作,因为上下文是从<Router>组件传递下来的,对吗?

class App extends React.Component {
constructor() {
super(...arguments);
}
render() {
const home = () => (<div>Home</div>);
const about = () => (<div>About</div>);
const { history } = this.context.router;
console.log("History", history);
return (
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<Route exact path="/" component={home} />
<Route path="/about" component={about} />
</div>
)
}
}
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('main')
);

但正如您在控制台输出中看到的那样,历史对象是未定义的。

只是为了澄清Azium的评论:

class App extends React.Component {
constructor() {
super(...arguments);
}
render() {
const home = () => (<div>Home</div>);
const about = () => (<div>About</div>);
const { history } = this.props;
console.log("History", history);
return (
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<Route exact path="/" component={home} />
<Route path="/about" component={about} />
</div>
)
}
}
const AppWithRouter = withRouter(App);
ReactDOM.render(
<Router>
<AppWithRouter />
</Router>,
document.getElementById('main')
);

withRouter为您提供道具上的匹配,位置和历史记录。

最新更新