Js div在React组件中滚动到底部

时间:2017-12-17 20:05:09

标签: javascript reactjs scroll

通过编写函数scrollToBot我遇到了问题。该函数将由componentDidMount和componentDidUpdate调用。但是div并没有滚动。我不知道这个功能有什么不对。我必须使用JQuery来实现这个功能吗?

提前致谢。

scrollToBot(){
    console.log(this.textAreaDiv.offsetHeight); // 4000
    if(this.textAreaDiv.offsetHeight>3000){
        console.log("should scoll!!!!!!!!!!!!!!"); // showed
        this.textAreaDiv.scrollTop=2000;
    }
    console.log('run scrollTo'); // showed
}

componentDidMount(){
    this.scrollToBot();
}

componentDidUpdate(){
    this.scrollToBot();
}

2 个答案:

答案 0 :(得分:1)

这在React中不起作用,因为它使用Virtual DOM来访问您需要使用Refs的真实DOM元素,如React Documents

中所述

答案 1 :(得分:1)

在JSX中使用ref以便从反应组件的其余部分访问dom元素。

示例:

...
textAreaDiv: null

setInputRef(dom){
    this.textAreaDiv = dom
}

render(){
    <div ref={this.setInputRef}/>
}

`

相关问题