ReactJS如何滚动到一个元素

JavaScript

阿飞神无

2020-03-11

我有一个聊天小部件,每次我向上滚动时,它都会拉出一系列消息。我现在面临的问题是,在加载消息时,滑块保持固定在顶部,我希望它专注于上一个数组中的最后一个索引元素。我发现可以通过传递索引来创建动态引用,但是我还需要知道要使用哪种滚动功能才能实现这一点

 handleScrollToElement(event) {
    const tesNode = ReactDOM.findDOMNode(this.refs.test)
    if (some_logic){
      //scroll to testNode      
    }
  }

  render() {

    return (
      <div>
        <div ref="test"></div>
      </div>)
  }

第698篇《ReactJS如何滚动到一个元素》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

9个回答
神奇小小伽罗 2020.03.11
 <div onScrollCapture={() => this._onScrollEvent()}></div>

 _onScrollEvent = (e)=>{
     const top = e.nativeEvent.target.scrollTop;
     console.log(top); 
}
木心小哥 2020.03.11

对我有用的是:

class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef(); // Create a ref    
    }

    // Scroll to ref function
    scrollToMyRef = () => {
        window.scrollTo({
            top:this.myRef.offsetTop, 
            // behavior: "smooth" // optional
        });
    };

    // On component mount, scroll to ref
    componentDidMount() {
        this.scrollToMyRef();
    }

    // Render method. Note, that `div` element got `ref`.
    render() {
        return (
            <div ref={this.myRef}>My component</div>
        )
    }
}
猿小胖 2020.03.11

您可以使用类似 componentDidUpdate

componentDidUpdate() {
  var elem = testNode //your ref to the element say testNode in your case; 
  elem.scrollTop = elem.scrollHeight;
};
乐猪猪 2020.03.11

2019年7月-专用挂钩/功能

专用的挂钩/函数可以隐藏实现细节,并为您的组件提供简单的API。

React 16.8 +功能组件

const useScroll = () => {
  const htmlElRef = useRef(null)
  const executeScroll = () => window.scrollTo(0, htmlElRef.current.offsetTop)

  return [executeScroll, htmlElRef]
}

在任何功能组件中使用它。

const ScrollDemo = () => {
    const [executeScroll, htmlElRef] = useScroll()
    useEffect(executeScroll, []) // Runs after component mounts

    return <div ref={htmlElRef}>Show me</div> 
}

完整演示

React 16.3 +类组件

const utilizeScroll = () => {
  const htmlElRef = React.createRef()
  const executeScroll = () => window.scrollTo(0, htmlElRef.current.offsetTop)

  return {executeScroll, htmlElRef}
}

在任何类组件中使用它。

class ScrollDemo extends Component {
  constructor(){
    this.elScroll = utilizeScroll()
  }

  componentDidMount(){
    this.elScroll.executeScroll()
  }

  render(){
    return <div ref={this.elScroll.htmlElRef}>Show me</div> 
  }
} 

完整演示

Green理查德 2020.03.11

您也可以使用scrollIntoView方法滚动到给定的元素。

handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
 if (some_logic){
  tesNode.scrollIntoView();
  }
 }

 render() {
  return (
   <div>
     <div ref="test"></div>
   </div>)
}
Jim猿 2020.03.11

最终将不建议使用findDOMNode。

首选方法是使用回调引用。

github eslint

乐十三 2020.03.11

您可以这样尝试:

 handleScrollToElement = e => {
    const elementTop = this.gate.offsetTop;
    window.scrollTo(0, elementTop);
 };

 render(){
  return(
      <h2 ref={elem => (this.gate = elem)}>Payment gate</h2>
 )}
EvaGil 2020.03.11

我可能参加聚会的时间很晚,但是我试图以正确的方式对项目实施动态引用,并且找到了所有答案,直到知道并不能完全满足我的喜好,所以我想出了一个我认为是的解决方案简单,并使用本机和推荐的反应方式来创建引用。

有时,您会发现文档的编写方式假定您具有已知的视图数量,并且在大多数情况下该数量是未知的,因此在这种情况下,您需要一种解决问题的方法,对所需数量的未知视图创建动态引用在课堂上展示

因此,我能想到并能完美工作的最简单的解决方案是执行以下操作

class YourClass extends component {

state={
 foo:"bar",
 dynamicViews:[],
 myData:[] //get some data from the web
}

inputRef = React.createRef()

componentDidMount(){
  this.createViews()
}


createViews = ()=>{
const trs=[]
for (let i = 1; i < this.state.myData.lenght; i++) {

let ref =`myrefRow ${i}`

this[ref]= React.createRef()

  const row = (
  <tr ref={this[ref]}>
<td>
  `myRow ${i}`
</td>
</tr>
)
trs.push(row)

}
this.setState({dynamicViews:trs})
}

clickHandler = ()=>{

//const scrollToView = this.inputRef.current.value
//That to select the value of the inputbox bt for demostrate the //example

value=`myrefRow ${30}`

  this[value].current.scrollIntoView({ behavior: "smooth", block: "start" });
}


render(){

return(
<div style={{display:"flex", flexDirection:"column"}}>
<Button onClick={this.clickHandler}> Search</Button>
<input ref={this.inputRef}/>
<table>
<tbody>
{this.state.dynamicViews}
<tbody>
<table>
</div>


)

}

}

export default YourClass

这样,滚动条将转到您要查找的任何行。

欢呼,希望对别人有帮助

Sam凯卡卡西 2020.03.11

只需找到您已经确定的元素的最高位置https://www.w3schools.com/Jsref/prop_element_offsettop.asp,然后通过scrollTo方法https://www.w3schools.com/Jsref/met_win_scrollto.asp滚动到该位置

这样的事情应该起作用:

handleScrollToElement(event) {
  const tesNode = ReactDOM.findDOMNode(this.refs.test)
  if (some_logic){
    window.scrollTo(0, tesNode.offsetTop);
  }
}

render() {

  return (
    <div>
      <div ref="test"></div>
    </div>)
}

更新:

因为阵营v16.3React.createRef()优选

constructor(props) {
  super(props);
  this.myRef = React.createRef();
}

handleScrollToElement(event) {
  if (<some_logic>){
    window.scrollTo(0, this.myRef.current.offsetTop);
  }
}

render() {

  return (
    <div>
      <div ref={this.myRef}></div>
    </div>)
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android