最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - scrollTop not working in react js - Stack Overflow

programmeradmin0浏览0评论

I am using React with basic JavaScript. scrollTop seems not to be working at all. I am using the code below:

const node = ReactDOM.findDOMNode(this)
const $container = node.getElementsByClassName('ments')
$container[0].scrollTop = 10

After executing this code, scrollTop is not working. There is already working CSS in place, with all scrolling visible for the container element.

I am using React with basic JavaScript. scrollTop seems not to be working at all. I am using the code below:

const node = ReactDOM.findDOMNode(this)
const $container = node.getElementsByClassName('ments')
$container[0].scrollTop = 10

After executing this code, scrollTop is not working. There is already working CSS in place, with all scrolling visible for the container element.

Share Improve this question edited Dec 12, 2017 at 16:23 Patrick Hund 20.3k12 gold badges71 silver badges95 bronze badges asked Dec 12, 2017 at 5:05 learning_vbalearning_vba 3802 gold badges4 silver badges15 bronze badges 2
  • Why are you mixing Javascript DOM handling with React. Also do you want to scroll only on a particular class element – Shubham Khatri Commented Dec 12, 2017 at 5:18
  • yes I am trying to scroll on particular class element. Is there any react library for scrolling or animation that I can use ? – learning_vba Commented Dec 12, 2017 at 20:22
Add a ment  | 

2 Answers 2

Reset to default 3

I think, you should remove findDOMNode and use ref, when you want to get DOMElement. One of the way to solve this problem below:

const homeStyles = {
  overflow: 'auto',
  width: 100,
  height: 100,
  border: '1px solid #333'
}

class Home extends React.Component{

  handleScrollTo = () => {
    this.container.scrollTop = 10;
  }

  render(){
    return (
      <div ref={ el => this.container = el} style={homeStyles}> 
        <a onClick={this.handleScrollTo}>ScrollTo</a> <br/><br/>
        content<br/>
         content<br />
         content<br />
         content<br />
         content<br />
         content<br />
         content<br />
         content<br />
         content<br />      
      </div>
    )
  }
}

Full working example: https://codesandbox.io/s/v8z7r0pxw5

In your method do something like this

ponentDidMount () {
  window.scrollTo(0, 0);
}

render () {
  return (
     <div>
        <p>text here</p>
        <p>text here</p>
        <p>text here</p>
        <p>text here</p>
        <button onClick={this.onScrollToTop}>Take Me To Top</button>
     </div>
  );
}
发布评论

评论列表(0)

  1. 暂无评论