Estoy tratando de asignar un valor aleatorio a "customStyle.top" dentro de mi bucle for, pero el valor customStyle.top/customStyle.Left no cambia aleatoriamente. Mi código es el siguiente:
import React from "react"; const customStyle = { position: "absolute", top: "", left: "", zIndex: "initial", color: "green" }; // Splitting Letters const SplitText = React.memo(({ str }) => { return ( <div> {str.split("").map((item, index) => { var randLeft = Math.floor(Math.random() * 1000); var randTop = Math.floor(Math.random() * 600); let letter = item; for (let i = 0; i < item; i++) { customStyle.top = +randTop + "px"; customStyle.left = +randLeft + "px"; letter = letter + i; } console.log(customStyle.top); return ( <div key={index} style={customStyle}> {letter} </div> ); })} </div> ); }); export default SplitText;enlace a mi CodeSandbox: Haga clic.!
Creo que olvidó agregar la palabra clave de length en su for loop .
Aquí está el código de trabajo:
import React from "react"; const customStyle = { position: "absolute", top: "", left: "", zIndex: "initial", color: "green" }; // Splitting Letters const SplitText = React.memo(({ str }) => { return ( <div> {str.split("").map((item, index) => { var randLeft = Math.floor(Math.random() * 1000); var randTop = Math.floor(Math.random() * 600); let letter = item; for (let i = 0; i < item.length; i++) { // item.length customStyle.top = +randTop + "px"; customStyle.left = +randLeft + "px"; letter = letter + i; } console.log(customStyle.top); return ( <div key={index} style={customStyle}> {letter} </div> ); })} </div> ); });Arreglé 2 errores.
customStyle . Cada vez que cambia un valor, lo está cambiando en todas partes. Por lo tanto, copie el valor o cree uno nuevo. Inserte ese valor en su salida.Código
import React from "react"; // Splitting Letters const SplitText = React.memo(({ str }) => { return ( <div> {str.split("").map((item, index) => { const style = { position: "absolute", top: Math.floor(Math.random() * 600) + 'px', left: Math.floor(Math.random() * 600) + 'px', zIndex: "initial", color: "green" }; return ( <div key={index} style={style}> {item} </div> ); })} </div> ); }); export default SplitText;