componentDidMount() {
  this.container = document.getElementById('container')
  const containerNode = ReactDOM.findDOMNode(this.container)
  if(containerNode) containerNode.scrollTop = 0
}


当我在组件中应用上述代码时,什么都没有发生,只是好奇这是什么错误?我没有使用ref,我需要document.getElementById('container')进行其他操作。

最佳答案

您应该避免使用document.getElementById。相反,您可能应该使用ref,如docs中所述

render(){
  <div id="container"
    ref={(container) => { this.container = container; }}
  />
}


然后在componentDidMount中,您可以执行此操作

componentDidMount() {
  this.container.scrollTop = 0
}

10-06 00:00
查看更多