简体   繁体   中英

How to create a vertical auto-scroll effect?

I'm new to reactjs. I'm good in javascript and jQuery, but dumb in ReactJS. I have this jQuery code and I need to make it work with reactjs. This function is supposed to auto-scroll the list vertically on a loop. But I don't have any idea how to do this in react.

function autoScroll(obj) {
    $(obj).find("container").animate({
        marginTop: "-28px"
    }, 500, function () {
        $(this).css({
            marginTop: "0px"
        }).find("li:first").appendTo(this);
    });
}
$(function () {
    setInterval('autoScroll(".container")', 3000);
})

Given my component

import React from 'react'

function List(props) {
   const lists = props.list
   const list_div = lists.map((lists, index) => {
      return (
         <li key={index}>{lists}</li>
      )
   })

   return(
      <ul className="container">{list_div}</ul>
   )
}

export default List

Will appreciate any help.

Step 1: Add ref to your components

 //Create ref for parent component
 const containerRef = React.createRef()


//Set the created Ref to the element
<ul className="container" ref={containerRef}>{list_div}</ul>

Step 2: Create refs to child components

//Create ref to child components
lists.map((list,index) => listsRef[index] = React.createRef())

Step 3: In your event (either click, load, etc), add this code to automatically scroll in one of the child component

 this.containerRef.current.scrollTo({
    top: listsRef[index].offsetTop,
    left: 0,
    behavior:'smooth'
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM