反应-URL中的链接是#[object%20HTMLParagraphElement]而不是#id

时间:2019-06-26 09:18:00

标签: javascript reactjs

我有一个函数,可以为固定的选项卡计算正确的位置,以便滚动至该位置,但是我注意到当它们滚动至该位置时,它将URL更改为#[object%20HTMLParagraphElement]而不是#idname。

以下是我的功能,当用户单击我的固定导航上的一个标签时,就会触发onClick

calculateScrollPosition (e) {
  const nav = document.querySelector('#navbar')
  if (!nav) return

  let navHeight = nav.getBoundingClientRect().height
  let section = document.querySelector(e.target.parentElement.dataset.link)
  let sectionTop = section.getBoundingClientRect().top

  const body = document.body
  const docEl = document.documentElement

  const scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop
  const clientTop = docEl.clientTop || body.clientTop || 0
  const top = Math.round(sectionTop + scrollTop - clientTop)

  let scrollHeight = top - navHeight
  window.scroll(0, scrollHeight)
  window.location.hash = e.target
  e.preventDefault()
}

1 个答案:

答案 0 :(得分:1)

window.location.hash = e.target

您正在为其分配目标元素,而不是目标元素的ID。

window.location.hash = e.target.id

或者目标元素的某些其他功能我们一无所知,因为您没有在示例代码中包含任何HTML。