Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

506
Visualizações
¿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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda