在react内,如何实现点击某按钮后div盒子内的横向滚动条向左或向右滑动

// 方案一

import React, { useRef, useState } from 'react';
import './App.css';
 
function App() {
  const scrollContainerRef = useRef(null);
  const [scrollPosition, setScrollPosition] = useState(0);
 
  const scrollLeft = () => {
    const container = scrollContainerRef.current;
    if (container) {
      const maxScroll = container.scrollWidth - container.clientWidth;
      const newPosition = Math.max(0, scrollPosition - 100); // 滑动量,可以根据需要调整
      setScrollPosition(newPosition);
      container.scrollLeft = newPosition;
    }
  };
 
  const scrollRight = () => {
    const container = scrollContainerRef.current;
    if (container) {
      const maxScroll = container.scrollWidth - container.clientWidth;
      const newPosition = Math.min(maxScroll, scrollPosition + 100); // 滑动量,可以根据需要调整
      setScrollPosition(newPosition);
      container.scrollLeft = newPosition;
    }
  };
 
  return (
    <div className="App">
      <button onClick={scrollLeft}>Scroll Left</button>
      <button onClick={scrollRight}>Scroll Right</button>
      <div
        ref={scrollContainerRef}
        className="scroll-container"
        onScroll={(e) => setScrollPosition(e.target.scrollLeft)}
      >
        {/* Your content here */}
        <div style={{ width: '3000px', height: '100px' }}>
          Long content to enable scrolling
        </div>
      </div>
    </div>
  );
}
 
export default App;


// 方案二

import React, { useRef, useState } from 'react';
import './App.css';
 
function App() {
  const scrollContainerRef = useRef(null);
  const [scrollLeft, setScrollLeft] = useState(0);
 
  const handleScrollLeft = (direction) => {
    const container = scrollContainerRef.current;
    if (container) {
      const newScrollLeft = container.scrollLeft + (direction === 'left' ? -100 : 100);
      setScrollLeft(newScrollLeft);
      container.scrollTo({
        left: newScrollLeft,
        behavior: 'smooth'
      });
    }
  };
 
  return (
    <div className="App">
      <div
        ref={scrollContainerRef}
        style={{ overflowX: 'auto', whiteSpace: 'nowrap', width: '300px' }}
      >
        <div style={{ width: '1000px', height: '50px' }}>
          这里是可以滚动的内容...
        </div>
      </div>
      <button onClick={() => handleScrollLeft('left')}>向左滑动</button>
      <button onClick={() => handleScrollLeft('right')}>向右滑动</button>
    </div>
  );
}
 
export default App;

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值