深度剖析React中如何實現系統內外的跳轉
阿新 • • 發佈:2018-12-31
1、系統內部的跳轉
- 效果:單擊"跳轉"按鈕,可以跳轉到系統內指定的頁面
第一步:定義router
import Login_Index from '../components/Login_Index.js';//引入頁面
<Route path="/Login_Index " component={Login_Index }/> //path:單純路徑
(1)程式碼實現:第一種方式,使用link to,進一步瞭解link用法請參考:
<Link to="/Login_Index"> <Button style={buttoncolor} size="large">跳轉</Button></Link>
(2)程式碼實現:第二種方式,使用react-router,
//第一步:引入 PropTypes
import PropTypes from "prop-types";
//第二步:設定contextTypes 、constructor(props, context)
static contextTypes = {
router: PropTypes.object
}
constructor(props, context) {
super(props, context)
}
//第三步:根據判斷,進行對應跳轉 <Button onClick={this.onclick_button.bind(this, '跳轉')}>跳轉</Button> //單擊執行函式onclick_button //定義單擊函式事件onclick_button onclick_button(button_name) { if (button_name == 'react-router跳轉') { this.context.router.history.push("跳轉");//路由跳轉 } }
2、系統外部的跳轉
- 效果:單擊"跳轉"按鈕,可以跳轉到系統外部的頁面,比如百度
第一步:定義router
import Login_Index from '../components/Login_Index.js';//引入頁面
<Route path="/Login_Index " component={Login_Index }/> //path:單純路徑
(1)程式碼實現:第一種方式,使用link to,進一步瞭解link用法,請參考
https://blog.csdn.net/zrcj0706/article/details/78577328<Link to="https://www.baidu.com/"> <Button style={buttoncolor} size="large">跳轉</Button></Link>
(2)程式碼實現:第二種方式,使用window.location.href
//根據判斷,進行對應跳轉
<Button onClick={this.onclick_button.bind(this, '跳轉')}>跳轉</Button> //單擊執行函式onclick_button
//定義單擊函式事件onclick_button
onclick_button(button_name) {
if (button_name == 'react-router跳轉') {
window.location.href = 'https://www.baidu.com/'; //window.location.href跳轉
}
}