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
相关产品推荐
相关产品推荐

