![](/img/trans.png)
[英]React <Nav.Link href > trying to link and scroll to one of the <div> in another component on the same page
[英]React: Link to a div on another html page
我有链接
<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 仍然为空。 如果组件已安装,它如何为空?
使用链接组件也不起作用,因为我需要将它放在路由器中,我已经使用过
<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()
}
}
我不确定您要完成什么,但我可以给您一些与您所写内容相关的提示:
首先,React 等价于document.getElementById()
是ReactDOM.findDOMNode(this.nodeName)
并且你必须记住import ReactDOM from 'react-dom';
为了使用这个方法,你必须在你的 div 上创建一个 ref ref={ ref => this.nodeName = ref }
还有一个提示,我不熟悉您如何在 DOM 中组织组件,但我个人不在我的 JSX 中使用 html 链接。 您可以简单地将onClick={this.myClickFunction}
添加到任何 div。 这为处理 JS 中的点击提供了更多自由。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.