本文記錄了使用react的時(shí)候想要實(shí)現(xiàn)錨點(diǎn)跳轉(zhuǎn)的解決方案哀托。
傳統(tǒng)解決方案
<a href="#scroll">
<button className="button">
<i className="text">跳轉(zhuǎn)</i>
</button>
</a>
<div>
<a name="scroll"></a>
<p>跳到這里</p>
</div>
用這種傳統(tǒng)的方式铺然,如果是基于browserHistory寝优,路徑上加了hash值晃危,但是并不會(huì)跳轉(zhuǎn)到想要的錨點(diǎn)位置斋否。
localhost:3000/demo#scroll
如果是基于hashHistory梨水,雖然會(huì)跳轉(zhuǎn)到想要的錨點(diǎn)位置,但是路徑改變了茵臭。
localhost:3000/#/demo
=>
localhost:3000/#/scroll
基于browserHistory的解決方案
solugebefola提出的解決方案
scrollToAnchor() {
let anchorName = this.props.location.hash;
if (anchorName) {
anchorName = anchorName.replace("#","");
let anchorElement = document.getElementById(anchorName);
if(anchorElement) { anchorElement.scrollIntoView(); }
}
}
但是如果基于hashHistory的疫诽,就不能通過hash值來判斷
基于hashHistory的解決方案
不能用hash值,那就只能通過query的方式來實(shí)現(xiàn)啦~
scrollToAnchor() {
let anchorName = t.props.location.query.anchorName;
if (anchorName) {
let anchorElement = document.getElementById(anchorName);
if(anchorElement) { anchorElement.scrollIntoView(); }
}
}
Support
scrollIntoView