在a標簽下面添加一個按鈕並加上onClick事件,通過this.props.history.push這個函數跳轉到detail頁面。在路由組件中加入的代碼就是將history這個對象注冊到組件的props中去,然后就可以在子組件中通過props調用history的push方法跳轉頁面。
很多場景下,我們還需要在頁面跳轉的同時傳遞參數,在react-router-dom中,同樣提供了兩種方式進行傳參。
隱式傳參
此外還可以通過push函數隱式傳參。
修改home.js代碼如下:
在detail.js中,就可以使用this.props.history.location.state獲取home傳過來的參數:
componentDidMount() {
//console.log(this.props.match.params);
console.log(this.props.history.location.state);
}
跳轉后打開控制台可以看到參數被打印:
其他函數
replace
有些場景下,重復使用push或a標簽跳轉會產生死循環,為了避免這種情況出現,react-router-dom提供了replace。在可能會出現死循環的地方使用replace來跳轉:
this.props.history.replace('/detail');
goBack
場景中需要返回上級頁面的時候使用:
this.props.history.goBack();