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

518
Views
¿Cómo cambiar dinámicamente el valor de la propiedad de fila del área de texto de acuerdo con la entrada de texto? [En ReactJS]

Hasta ahora he hecho esto:

 <textarea rows='2' onChange={e => setSomething(e.target.value)} className='form-control text-area ' value={something} placeholder='write something'> </textarea>

producción:

ingrese la descripción de la imagen aquí

Requisito esperado:

Necesito cambiar el valor de la propiedad de fila dinámicamente de acuerdo con la línea de texto. Si el número de líneas de texto aumenta, el valor de la propiedad de la fila también aumentará. Pero si son más de 8, entonces tenemos que usar la barra de desplazamiento.

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

0

Supongo que lo que realmente quieres es cambiar el tamaño dinámicamente del área de texto para que coincida con el contenido:

  • Puede hacerlo configurando la height del área de texto en auto y luego en el valor de textarea.scrollHeight .
  • Si no desea que el usuario pueda hacer que el área de texto sea más pequeña que eso, también establezca minHeight en ese valor:
  • Puede limitar la altura máxima con maxHeight y asegurarse de que minHeight no esté configurado en un valor mayor que ese. Más allá de eso, aparecerán barras de desplazamiento:

 function resizeTextArea(textarea) { const { style, value } = textarea; // The 4 corresponds to the 2 2px borders (top and bottom): style.height = style.minHeight = 'auto'; style.minHeight = `${ Math.min(textarea.scrollHeight + 4, parseInt(textarea.style.maxHeight)) }px`; style.height = `${ textarea.scrollHeight + 4 }px`; } const textarea = document.getElementById('textarea'); textarea.addEventListener('input', () => { resizeTextArea(textarea); });
 #textarea { display: block; margin: 0; padding: 8px; border: 2px solid black; width: 100%; box-sizing: border-box; resize: vertical; }
 <textarea id="textarea" style="max-height: 140px; "></textarea>

Una versión mejorada de no reduciría el área de texto si el usuario lo ha expandido manualmente, a menos que lo reduzca para ajustarse al contenido. Sin embargo, aún se expandiría automáticamente si el contenido se vuelve más grande que la altura definida por el usuario:

 function resizeTextArea(textarea, userDefinedHeight = 0) { const { style, value } = textarea; // The 4 corresponds to the 2 2px borders (top and bottom): style.height = style.minHeight = 'auto'; style.minHeight = `${ Math.min(textarea.scrollHeight + 4, parseInt(textarea.style.maxHeight)) }px`; style.height = `${ Math.max(textarea.scrollHeight + 4, userDefinedHeight) }px`; } const textarea = document.getElementById('textarea'); let userDefinedHeight = 0; textarea.addEventListener('input', () => { resizeTextArea(textarea, userDefinedHeight); }); textarea.addEventListener('mouseup', () => { const { height, minHeight } = textarea.style; // Do not shrink beyond user-defined values (if they expand it manually), // but go back to auto-resizing if they shrink it back to the content size: userDefinedHeight = height === minHeight ? 0 : parseInt(height, 10); });
 #textarea { display: block; margin: 0; padding: 8px; border: 2px solid black; width: 100%; box-sizing: border-box; resize: vertical; }
 <textarea id="textarea" style="max-height: 140px; "></textarea>

about 4 years ago · Juan Pablo Isaza Report

0

Puede hacer esto si establece la propiedad de fila dinámicamente de acuerdo con la cantidad de nuevas líneas que hay como:

Demo en vivo

Demostración de Codesandbox

 import { useState } from "react"; import "./styles.css"; export default function App() { const [rows, setRows] = useState(2); const [value, setValue] = useState(""); function setTextAreaInput(e) { const val = e.target.value; setValue(val); const newLines = val.match(/\n/g)?.length; if (!newLines) setRows(2); else if (newLines < 8) setRows(newLines + 1); else setRows(8); } return ( <div> <textarea rows={rows} onChange={(e) => setTextAreaInput(e)} className="form-control text-area " value={value} placeholder="write something"></textarea> </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!