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

React for循环内为customStyle.top赋随机值未随机生效问题求助

问题原因

  • 你定义的customStyle是模块级别的引用类型对象,所有循环生成的div元素共用同一个对象的引用,每次修改customStyle的属性都会覆盖之前的赋值,最终所有元素拿到的都是最后一次循环设置的样式值,自然不会呈现每个元素独立随机的效果。
  • 代码中的for循环逻辑错误:循环判断条件是i < item,而item是拆分出来的单个字符,除非是数字字符,否则转成数值后为NaN,循环体根本不会执行,top和left的赋值代码绝大多数情况下都不会触发。

修复方案

直接在每次map遍历的时候创建独立的样式对象,废弃全局共用的customStyle,删除无效的for循环即可,修复后代码如下:

import React from "react";

// Splitting Letters
const SplitText = React.memo(({ str }) => {
  return (
    <div>
      {str.split("").map((item, index) => {
        const randLeft = Math.floor(Math.random() * 1000);
        const randTop = Math.floor(Math.random() * 600);
        // 每次循环创建独立的样式对象
        const customStyle = {
          position: "absolute",
          top: `${randTop}px`,
          left: `${randLeft}px`,
          zIndex: "initial",
          color: "green"
        };
        return (
          <div key={index} style={customStyle}>
            {item}
          </div>
        );
      })}
    </div>
  );
});

export default SplitText;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:24:05