// main.js
class Main extends React.Component {
render () {
return (
<Router>
<div>
<Switch>
<Route exact path="/" component={First} ></Route>
<Route path="/home" component={Homes} ></Route>
</Switch>
</div>
</Router>
)
}
}
export default Main
// First.js
class First extends React.Component {
render () {
return (
<div>
<div>first page</div>
// 将Login组件作为First的子组件,点击跳转至/home
<Login />
</div>
)
}
}
export default First
// login.js
import { withRouter } from 'react-router-dom';
class Login extends React.Component {
handleLogin = () => {
// 如果Login组件没有使用withRouter,这里将取不到history、match、location
let {history} = this.props
history.push('/home')
}
render () {
return (
<div>
<div>login</div>
<div onClick={this.handleLogin}>点击去home</div>
</div>
)
}
}
// Login组件不在<Route >的匹配列表里,要想访问this.props里的属性,写法如下:
export default withRouter(Login)
网友评论