简体   繁体   English

使用 Typescript 将 React 中输入的值复制到剪贴板

[英]Copy to clipboard a value from an input in React with Typescript

Having the following code snippet:具有以下代码片段:

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

The button, when clicked, must copy the value from input, which is already set to test .单击该按钮时,必须从输入中复制值,该值已设置为test

So, copyToClipboard must perform the operation:因此, copyToClipboard必须执行以下操作:

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

How I've tried:我是如何尝试的:

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>

It has an error saying: Object is possibly 'null'.ts(2531) for textAreaRef.current.select();它有一个错误说: Object is possibly 'null'.ts(2531) for textAreaRef.current.select(); . . I'm using React with Typescript.我将 React 与 Typescript 一起使用。

textAreaRef.current is possibly null . textAreaRef.current可能是null In fact, null is the default initial value you've set the textAreaRef to.事实上, null是您设置textAreaRef的默认初始值。

const textAreaRef = useRef(null);

What the warning is saying that textAreaRef.current is possibly null but you are accessing it in an unsafe way in order to invoke the select function.警告的意思是textAreaRef.current可能是null但您以不安全的方式访问它以调用select function。

You might be able to use the Optional Chaining operator ( Typescript 3.7 ):也许可以使用可选链接运算符( Typescript 3.7 ):

textAreaRef.current?.select();

Or you just use a null-check/guard-clause:或者你只使用一个空检查/保护子句:

textAreaRef.current && textAreaRef.current.select();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM