// 方案一

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;

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐