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

99
Views
Copie al portapapeles un valor de una entrada en React con Typescript

Tener el siguiente fragmento de código:

 <div> <Input id='id' disabled value='test' /> <Button onClick={copyToClipboard} /> </div>

El botón, cuando se hace clic, debe copiar el valor de la entrada, que ya está configurado para test .

Entonces, copyToClipboard debe realizar la operación:

 const copyToClipboard = () => { ... };

Como lo he probado:

 import { useRef, useState } from 'react'; ... const [copySuccess, setCopySuccess] = useState(''); const textAreaRef = useRef(null); function copyToClipboard(e) { textAreaRef.current.select(); document.execCommand('copy'); e.target.focus(); setCopySuccess('Copied!'); } ... <div> <Input ref={textAreaRef} id='id' value='test' /> <Button onClick={copyToClipboard} /> </div>

Tiene un error que dice: Object is possibly 'null'.ts(2531) for textAreaRef.current.select(); . Estoy usando React con Typescript.

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

0

textAreaRef.current es posiblemente null . De hecho, null es el valor inicial predeterminado en el que ha establecido textAreaRef .

 const textAreaRef = useRef(null);

Lo que dice la advertencia es que textAreaRef.current es posiblemente null , pero está accediendo a él de una manera insegura para invocar la función de select .

Es posible que pueda usar el operador de encadenamiento opcional ( Typescript 3.7 ):

 textAreaRef.current?.select();

O simplemente usa una cláusula de verificación/guardia nula:

 textAreaRef.current && textAreaRef.current.select();
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!