Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Cómo configurar el efecto de escritura multilínea para reaccionar con retraso entre líneas

Creé un componente basado en clases en React que inicia un efecto de escritura de varias líneas en la carga.

Está funcionando bien, pero el problema es que ambas líneas comienzan a escribirse simultáneamente, lo que tiene sentido dada la naturaleza de cómo se ejecuta setTimout.

Entonces, estoy buscando ideas/sugerencias sobre cómo hacer que espere a que termine de escribirse la primera línea antes de pasar a la siguiente.

 import React from 'react' import TerminalCursor from 'icons/TerminalCursor' import TerminalPrompt from 'icons/TerminalPrompt' import { v4 as uuidv4 } from 'uuid' type MyProps = {} type MyState = { introArray: string[] } class Terminal extends React.Component<MyProps, MyState> { state: MyState = { introArray: [], } componentDidMount() { // Data to import from sanity const starterArray = [ 'The very first line that needs to finish typing before going to the next line', 'The second line that needs to start being typed after the first line', ] const createTypingEffect = (text: string, index: number) => { for (let i = 0; i < text.length; i++) { setTimeout(() => { let arrayCopy = this.state.introArray.slice() this.setState((state) => ({ introArray: [...state.introArray.slice(0, index), arrayCopy[index] + text[i], ...state.introArray.slice(index + 1)], })) }, 100 * i) } } starterArray.forEach((starterText, starterIndex) => { // Setting empty string for each line in starterArray so we dont get undefined as first character this.setState((state) => ({ introArray: [...state.introArray, ''], })) // Need to wait for first line to finish typing before starting the second line createTypingEffect(starterText, starterIndex) }) } render() { return ( <div className="w-1/2 h-1/2 p-5 flex items-start justify-start bg-clip-padding bg-slate-900 backdrop-filter backdrop-blur-xl bg-opacity-60 border border-gray-900 rounded"> <div className="flex flex-col"> {this.state.introArray.map((introLine) => ( <div className="flex items-center" key={uuidv4()}> <TerminalPrompt /> <p className="text-white">{introLine}</p> </div> ))} {/* Actual prompt starts here */} <div className="flex"> <TerminalPrompt /> <TerminalCursor /> </div> </div> </div> ) } } export default Terminal

Aquí hay una demostración de sandbox (no estoy seguro de por qué algunos personajes se repiten en el sandbox, no tengo este problema en local...)

https://codesandbox.io/s/recursing-star-iohjw9?file=/src/Terminal.tsx

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Debe usar un enfoque asincrónico para este tipo de tareas (no verifiqué la lógica del efecto de escritura, solo hice que todo el proceso fuera asíncrono):

 import React from "react"; type MyProps = {}; type MyState = { introArray: string[]; }; class Terminal extends React.Component<MyProps, MyState> { state: MyState = { introArray: [] }; componentDidMount() { // Data to import from sanity const starterArray = [ "The very first line that needs to finish typing before going to the next line", "The second line that needs to start being typed after the first line" ]; const createTypingEffect = async (text: string, index: number) => { return Promise.all( text.split("").map( (c, i) => new Promise((res) => { setTimeout(() => { let arrayCopy = this.state.introArray.slice(); this.setState((state) => ({ introArray: [ ...state.introArray.slice(0, index), arrayCopy[index] + c, ...state.introArray.slice(index + 1) ] })); res(null); }, 100 * i); }) ) ); }; const cycle = async () => { let i = 0; for (const starterText of starterArray) { // Setting empty string for each line in starterArray so we dont get undefined as first character this.setState((state) => ({ introArray: [...state.introArray, ""] })); await createTypingEffect(starterText, i); i++; } }; cycle(); } render() { console.log(this.state.introArray); return ( <div className="w-1/2 h-1/2 p-5 flex items-start justify-start bg-clip-padding bg-slate-900 backdrop-filter backdrop-blur-xl bg-opacity-60 border border-gray-900 rounded"> <div className="flex flex-col"> {this.state.introArray.map((introLine, index) => ( <div className="flex items-center" key={index}> <p className="text-white">{introLine}</p> </div> ))} </div> </div> ); } } export default Terminal;

Puede usar varios enfoques para manejar la lógica asíncrona, aquí usé un enfoque Promise.all , dando un temporizador incremental al tiempo de espera, solo para seguir lo que estaba haciendo. Una solución alternativa es usar un bucle for...of simple y esperar un tiempo de espera prometido dentro. De esa manera, no necesita dar un tiempo incremental al tiempo de espera, ya que se ejecutarán de forma relativamente sincrónica .

La demostración de trabajo está AQUÍ (no se puede agregar un fragmento de código de trabajo aquí ya que SO no tiene soporte para TS)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!