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

142
Views
Renderizar una matriz de referencias

Tengo que realizar los siguientes pasos en una matriz:

  • Crear una matriz de referencias fuera del componente
  • crear un formulario
  • dentro del formulario, haga un mapa de la matriz y represente una entrada para cada elemento
  • la entrada (cuando está enfocada) al presionar "enter" pone en foco la siguiente entrada si hay alguna, de lo contrario, envía el formulario

Mi código es el siguiente:

 const array = new Array(5).fill(createRef()); const Step1 = () => { return ( <> {/*Form */} <form style={{margin:30}} > {/*- inside the form make a map of the array and render an input for each element, - the input (when in focus) at the press of "enter" puts the next input in focus if there is any, otherwise it submits the form */} {array.map((item, index) => { return ( <input key={index} ref={item} type="text" placeholder={`Input ${index + 1}`} onKeyPress={(e) => { if (e.key === "Enter") { if (array[index + 1]) { array[index + 1].current.focus(); } else { e.preventDefault(); console.log("submit"); } } }} /> ); })} <button type="submit">Submit</button> </form> </> ) } export default Step1;

El último punto no funciona, ¿cómo puedo cambiar el código para que funcione? Resuelto

El único problema es que no puedo escribir en las entradas. Resuelto

Si quisiera usar un componente de entrada que toma la referencia a través de forwardRef.

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

0

Tienes dos problemas. El problema principal es su uso de Array#fill() que, cuando se usa así, llena la matriz con referencias a un solo objeto. Como tal, está terminando con una sola ref a la que asigna sucesivamente cada entrada. La solución es mapear la matriz y devolver una nueva ref en cada iteración.

 const array = new Array(5).fill(null).map(() => createRef()); // or const array = Array.from({length: 5}, () => createRef());

Su segundo problema es que enter envía automáticamente el formulario, por lo que debe preventDefault() en el nivel superior del bloque if .

 const { createRef } = React; const array = Array.from({length: 5}, () => createRef()); const Step1 = () => { function focusNextRef(e, index) { if (e.key === 'Enter') { e.preventDefault(); // <-- move preventDefault() if (array[index + 1]) { array[index + 1].current.focus(); } else { console.log('submit'); } } } return ( <div> <form style={{ margin: 30 }} > {array.map((item, index) => { return ( <input key={index} ref={item} type="text" placeholder={'Input ' + (index + 1)} onKeyPress={(e) => focusNextRef(e, index)} /> ); })} <button type="submit">Submit</button> </form> </div> ); }; ReactDOM.render( <Step1 />, document.getElementById('root') );
 <script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> <div id="root"></div>

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!