Considere la siguiente estructura:
.container { width: 200px; height: 100px; overflow: auto; overflow-y: hidden; } .container p { width: 300px; height: 100px; background-color: yellow; } <div class="container"> <p>Sample Text1, Sample Text2, Sample Text3</p> </div> <button onclick="handleScrollLeft()">Left</button> <button onclick="handleScrollRight()">Right</button>Debido a que estoy trabajando en ReactJS, mi código real se parece más a esto:
export function Slider() { const handleScrollLeft = () => { } const handleScrollRight = () => { } return ( <> <div className="container"> <p>Sample Text1, Sample Text2, Sample Text3</p> </div> <button onClick="handleScrollLeft">Left</button> <button onClick="handleScrollRight">Right</button> </> ); }Con esos 2 botones me gustaría cambiar el valor de desplazamiento (mover hacia la izquierda y hacia la derecha respectivamente). No estoy seguro de cómo manejar este tipo de cambio:
Estoy realmente confundido sobre qué enfoque es correcto, cualquier consejo o solución con más explicaciones sobre por qué sería apreciado
Puede usar el gancho useRef y el método element.scrollBy .
const STEP = 40; export function Slider() { const scrollable = useRef(null); const handleScrollLeft = () => { scrollable.current.scrollBy(-STEP, 0); } const handleScrollRight = () => { scrollable.current.scrollBy(STEP, 0); } return ( <> <div className="container" ref={scrollable}> <p>Sample Text1, Sample Text2, Sample Text3</p> </div> <button onClick="handleScrollLeft">Left</button> <button onClick="handleScrollRight">Right</button> </> ); }También puede usar estesandbox como ejemplo.