You need to enable JavaScript to run this app. 如何用按钮实现文本左右滚动?右侧按钮点击无响应求解决
优惠活动
大模型
产品
解决方案
定价
更多

如何用按钮实现文本左右滚动?右侧按钮点击无响应求解决

问题修复方案

核心问题点

  1. useEffect依赖缺失:原代码中useEffect仅在组件挂载时执行一次,后续scrollSubPosition变化不会触发滚动操作,导致状态更新后页面无反应。
  2. 滚动位置计算错误:
    • 左按钮的-Math.max(...)会导致滚动位置变为负数,不符合scrollLeft的取值规则(不能小于0)。
    • 右按钮固定限制最大值为500,无法适配实际内容的可滚动宽度,应该基于元素的scrollWidth和clientWidth计算最大滚动值。
  3. 事件绑定函数名不匹配:按钮的onClick绑定的函数名(handleLeftSlideClick/handleRightSlideClick)与定义的函数名(handleSubLeftSlideClick/handleSubRightSlideClick)不一致,导致点击无响应。

修正后的代码

import { useState, useEffect, useRef } from 'react';
import { Grid, KeyboardArrowLeft, KeyboardArrowRight } from '@mui/material';

// 假设styleSubTitleIconColor是已定义的函数
const styleSubTitleIconColor = (index) => '#333';

const ScrollableText = ({ index }) => {
  const [scrollSubPosition, setScrollSubPosition] = useState(0);
  const subContentRef = useRef(null); // 使用ref替代getElementById,更符合React规范

  useEffect(() => {
    if (subContentRef.current) {
      subContentRef.current.scroll({
        left: scrollSubPosition,
        behavior: 'smooth',
      });
    }
  }, [scrollSubPosition]); // 添加依赖,状态变化时触发滚动

  const handleSubLeftSlideClick = () => {
    // 左滚:最小滚动位置为0
    setScrollSubPosition(prev => Math.max(prev - 100, 0));
  };

  const handleSubRightSlideClick = () => {
    if (!subContentRef.current) return;
    // 右滚:最大滚动位置为内容总宽度 - 容器可视宽度
    const maxScroll = subContentRef.current.scrollWidth - subContentRef.current.clientWidth;
    setScrollSubPosition(prev => Math.min(prev + 100, maxScroll));
  };

  return (
    <Grid item xs={12}>
      <div style={{
        display: 'flex',
        alignItems: 'center',
        cursor: 'pointer',
      }}>
        <div style={{
          display: 'flex',
          cursor: 'pointer',
          margin: '0 auto 0 0', // 修正margin写法,原marginTop无效
          flexWrap: 'nowrap',
        }}>
          <KeyboardArrowLeft onClick={handleSubLeftSlideClick} />
        </div>
        <div
          ref={subContentRef} // 使用ref获取DOM元素,替代getElementById
          style={{
            overflow: 'hidden',
            width: '220px',
            letterSpacing: '0.5px',
            color: styleSubTitleIconColor(index),
            whiteSpace: 'nowrap'
          }}>
          List of fruits: apple, orange, papaya, grape, waterMelon, jackFruit
        </div>
        <div style={{
          display: 'flex',
          cursor: 'pointer',
          margin: '0 0 0 auto', // 修正margin写法
          flexWrap: 'nowrap',
        }}>
          <KeyboardArrowRight onClick={handleSubRightSlideClick} />
        </div>
      </div>
    </Grid>
  );
};

export default ScrollableText;

额外优化点

  • 使用React的useRef替代getElementById,避免全局DOM查询的潜在问题,更符合组件开发规范。
  • 修正按钮容器的margin写法,原marginTop: '0px auto'无效,改为左右margin实现按钮的分布对齐。
  • 右按钮的最大滚动位置改为动态计算,适配不同长度的文本内容,避免固定值导致的滚动不足或过度。

内容的提问来源于stack exchange,提问作者user1595

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 12:42:16