[英]How to create a vertical auto-scroll effect?
I'm new to reactjs.我是 reactjs 的新手。 I'm good in javascript and jQuery, but dumb in ReactJS.
我擅长 javascript 和 jQuery,但在 ReactJS 方面很笨。 I have this jQuery code and I need to make it work with reactjs.
我有这个 jQuery 代码,我需要让它与 reactjs 一起工作。 This function is supposed to auto-scroll the list vertically on a loop.
这个 function 应该在循环上自动垂直滚动列表。 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第 1 步:将
ref
添加到您的组件
//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第 2 步:为子组件创建 refs
//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第 3 步:在您的事件中(单击、加载等),添加此代码以自动滚动其中一个子组件
this.containerRef.current.scrollTo({
top: listsRef[index].offsetTop,
left: 0,
behavior:'smooth'
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.