因此处理路由器导航的<Link />
onClick的实现很简单:
const { history } = this.context.router;
history.push(to);
这是从github repo
中提取的所以在我的application中,它应该有效,因为上下文从<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')
);
但是正如你在控制台输出中看到的那样,历史对象是未定义的....
答案 0 :(得分:0)
只是为了澄清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
为您提供道具上的匹配,位置和历史记录。