You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中点击高亮映射项并自动延迟选中下一项的实现

实现方案

核心思路

通过状态管理当前高亮的索引,点击时触发初始高亮,再利用定时器按设定延迟依次切换到后续索引,同时注意清理定时器避免内存泄漏。

代码实现

import { useState, useRef, useEffect } from 'react';

const TextSequence = () => {
  // 示例数据源(可替换为你的JSON数据)
  const textArray = ['文本1', '文本2', '文本3', '文本4', '文本5'];
  // 当前高亮的索引,初始-1表示无高亮项
  const [currentIndex, setCurrentIndex] = useState(-1);
  // 存储定时器ID,用于清理避免内存泄漏
  const timerRef = useRef(null);

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      timerRef.current && clearInterval(timerRef.current);
    };
  }, []);

  // 点击文本的处理逻辑
  const handleTextClick = (index) => {
    // 清理旧定时器,防止多个定时器同时运行
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }
    // 设置当前点击项为高亮
    setCurrentIndex(index);

    // 启动自动切换定时器
    timerRef.current = setInterval(() => {
      setCurrentIndex(prev => {
        // 到达最后一项时停止定时器
        if (prev === textArray.length - 1) {
          clearInterval(timerRef.current);
          return prev;
        }
        // 切换到下一项
        return prev + 1;
      });
    }, 1000); // 自定义延迟时间,这里设为1秒
  };

  return (
    <div>
      {textArray.map((text, index) => (
        <Text
          key={index}
          content={text}
          isHighlighted={currentIndex === index}
          onClick={() => handleTextClick(index)}
        />
      ))}
    </div>
  );
};

// 自定义Text组件(可根据你的需求调整样式)
const Text = ({ content, isHighlighted, onClick }) => {
  return (
    <span
      onClick={onClick}
      style={{
        padding: '8px 12px',
        margin: '0 4px',
        cursor: 'pointer',
        backgroundColor: isHighlighted ? '#ffd700' : 'transparent',
        borderRadius: '4px',
        transition: 'background-color 0.3s ease'
      }}
    >
      {content}
    </span>
  );
};

export default TextSequence;

关键细节

  • 定时器管理:用useRef存储定时器ID,在新点击和组件卸载时清理旧定时器,避免冲突和内存泄漏。
  • 状态更新逻辑:在setCurrentIndex的回调中判断是否到达数组末尾,到达则终止定时器。
  • 样式分离:通过isHighlighted属性传递高亮状态,让Text组件独立处理样式逻辑,保持代码解耦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:45:31