使用按钮在Reactjs中进行水平滚动

7
我正在使用左右按钮在div元素上制作水平滚动。我最初使用引用(refs)实现了相同的效果。
onClickLeft = () => {
    this.props.refELement.current.scrollLeft -= 300;
}
onClickRight = () => {
    this.props.refElement.current.scrollLeft += 300;
}

但我似乎找不到设置动画持续时间的方法。

使用jQuery,可以通过以下方式实现:

$('.swipeRight').click(function(){
     $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});

$('.swipeLeft').click(function(){
     $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});

但是这段代码在ReactJS中无法重现。

我想在ReactJS中基本实现这个

有什么帮助吗?


你想分享你的React代码吗? - curious.netter
1个回答

12
你可以使用这段代码。

document.getElementById('left-button').onclick = function () {
   scrollLeft(document.getElementById('content'), -300, 1000);   
}

document.getElementById('right-button').onclick = function () {
   scrollLeft(document.getElementById('content'), 300, 1000);   
}
    
function scrollLeft(element, change, duration) {
    var start = element.scrollLeft,
        currentTime = 0,
        increment = 20;
        
        console.log(start)
        
    var animateScroll = function(){        
        currentTime += increment;
        var val = Math.easeInOutQuad(currentTime, start, change, duration);
        element.scrollLeft = val;
        if(currentTime < duration) {
            setTimeout(animateScroll, increment);
        }
    };
    animateScroll();
}

//t = current time
//b = start value
//c = change in value
//d = duration
Math.easeInOutQuad = function (t, b, c, d) {
  t /= d/2;
 if (t < 1) return c/2*t*t + b;
 t--;
 return -c/2 * (t*(t-2) - 1) + b;
};
.left{
 float: left; 
 width: 30%;
 height: 200px;
 border: 1px solid black;
}

.internal{
 width: 31.75%;
 height: 100%;
 border: 1px solid black;
 display: inline-block;
}

.center{
 float: left; 
 width: 38.9%;
 height: 200px;
 border: 1px solid black;
 margin: 1px;
 overflow: hidden;
 /*will change this to hidden later to deny scolling to user*/
 white-space: nowrap;
}

.right{
 float: right; 
 width: 30%;
 height: 200px;
 border: 1px solid black;
}
<div class="left">
  left div
  <button id="left-button">
    swipe left
  </button>
</div>
<div class="center" id="content">
<div class=internal>
  div 1
</div>
 <div class=internal>
  div 2
</div>
 <div class=internal>
  div 3
</div>
 <div class=internal>
  div 4
</div>
 <div class=internal>
  div 5
</div>
 <div class=internal>
  div 6
</div>
 <div class=internal>
  div 7
</div>
 <div class=internal>
  div 8
</div>
</div>
<div class="right">
<button id="right-button">
    swipe right
  </button>
  right div
</div>

基于这段代码


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接