我在React中创建了一个固定的导航栏,但是当我单击它上的链接时,窗口滚动得太远,导航栏覆盖了内容的顶部。我试图动态计算导航器的高度,并在滚动条中考虑到这一点,但它仍在错误的位置。
import React from 'react'
import { string } from 'prop-types'
class FixedNav extends React.Component {
constructor(props){
super(props)
this.handleClick = this.handleClick.bind(this)
}
shouldComponentUpdate (nextProps) {
return nextProps.navItems !== this.props.navItems
}
handleClick (e) {
const nav = document.querySelector('#fixedNav')
let navHeight = nav.getBoundingClientRect().height
let itemLink = document.querySelector(e.target.parentElement.dataset.link)
let scrollHeight = itemLink.offsetTop - navHeight
window.scroll(0, scrollHeight)
window.location.hash = e.target.parentElement.dataset.link
e.preventDefault()
}
createNavItems () {
const { navItems } = this.props
return navItems.map((item, key) => {
const itemLink = items[1].link
return (
<li key={key} data-link={itemLink}>
<a href={itemLink} data-link={itemLink} onClick={this.handleClick}>
<p>{ items[0] }</p>
</a>
</li>
)
})
}
render () {
const navItems = this.createNavItems()
return (
<div>
<ul id='side-navigation' className='side-nav'>
{navItems}
</ul>
</div>
)
}
}
FixedNav.propTypes = {
navItems: string.isRequired
}
export default FixedNav