我有一个链接
<a href="about.html#div2">Click me</a>
当我点击链接时,我会看到文档顶部的 about.html。
如果我已经访问 about.html 并在浏览器 (chrome) 的搜索栏中输入 about.html#div2,那么我的浏览器会转到特定的 div(div2)。
我尝试转到加载其他页面和 ComponentDidMount 内部的组件,添加类似的内容
var sectionName = window.location.hash.slice(1);
//then show the section
$('#' + sectionName ).show();
但由于某种原因 div 仍然为空。如果组件挂载了怎么会为null呢?
使用链接组件也不起作用,因为我需要将其放入路由器中,我已经使用了
<HashRouter>
<Link style={linkButton} to={about.html#div2}>Learn more</Link>
</HashRouter
但这似乎确实没有任何作用。
如何让浏览器通过另一个页面上的链接访问另一个页面上的 div。
更新
这就是我的 about 组件的本质
class About extends React.component {
constructor(){
var p = props;
var Style = {
display:'flex',
flexDirection:'column'
}
}
componentDidMount(){
var sectionName = window.location.hash.slice(1);
//then show the section
$('#' + sectionName ).show();
}
render(){
return (
<div style={Style}>
<Service id='div1' serv={Service1}/>
<Service id='div2' serv={Service2}/>
<Service id='div3' serv={Service3}/>
<Service id='div4' serv={Service4}/>
<Service id='div5' serv={Service5}/>
</div>
)
}
}
var Service = (props) => {
var serv = props.serv;
return (
<div id={props.id}>
....
</div>
)
}
最佳答案
您不应该同时使用 jQuery 和 React。他们正在尝试完成同样的事情(DOM 管理/操作)
只需使用 DOM 访问器来获取 id 并在 componentDidMount 中滚动
componentDidMount () {
const myId = window.location.hash.slice(1)
const elem = document.getElementById(myId).
if (elem) {
elem.scrollIntoView()
}
}
关于javascript - react : Link to a div on another html page,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56877876/