【问题标题】:how to add new line on to textarea on copy to clipboard?如何在复制到剪贴板时在 textarea 上添加新行?
【发布时间】:2020-02-26 22:15:10
【问题描述】:

这是我复制到剪贴板的代码,我使用的是 textarea,但是当我将复制的内容粘贴到代码上时,所有内容都在一行中:

const CopyButton = ({ text }: { text: string }) => {
  const init_val = 'Copy';
  const [btn_val, set_value] = useState(init_val);
  const copyToClipboard = () => {
    const textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
    set_value('Copied!');
    setTimeout(() => {
      set_value(init_val);
    }, 1500);
  };

  return (
    <button className='copy-to-clipboard' onClick={copyToClipboard}>
      {btn_val}
    </button>
  );
};

我正在考虑使用正则表达式解决这个问题,但不知道如何并且似乎无法找到解决方案。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您必须使用 white-space: pre,因为 HTML 会删除空格。你可以试试下面的代码:

    const CopyButton = ({ text }: { text: string }) => {
    const init_val = 'Copy';
    const [btn_val, set_value] = React.useState(init_val);
    const copyToClipboard = () => {
      const textField = document.createElement('textarea');
      var newParagraph = document.createElement('p');
      var newContent = document.createTextNode("Samson's SR500 headphones offer exceptional sonic \nclarity and comfort in a durable, lightweight design \nperfect for studio and movile applications.");
      newParagraph.appendChild(newContent)
      document.body.appendChild(newParagraph);
      document.body.style ="white-space: pre";
      textField.select();
      document.execCommand('copy');
      textField.remove();
      set_value('Copied!');
      setTimeout(() => {
        set_value(init_val);
      }, 1500);
    };
    
    return (
      <div>
        <button className='copy-to-clipboard' onClick={copyToClipboard}>
            {btn_val}
        </button>
      </div>
    
    
     );
    };
    

    参考文献:

    【讨论】:

      【解决方案2】:

      你需要使用textField.innerHTMLtextField.textContent,textField.innerText会删除某些字符,比如换行。

      使用 innerHTML 时要小心,因为这将允许复制功能的用户在您的网站中插入他们自己的 HTML,这可能会导致跨站脚本 (XSS) 问题。

      【讨论】:

        【解决方案3】:

        正如您在我的代码中看到的那样,我正在使用 innerText,我深入研究并尝试使用 textContent 并且它起作用了,只需在我的代码中将 innerText 替换为 textContent:

        textField.textContent = text;
        

        【讨论】:

        • @i am gpbaculio 选择此作为最佳答案。
        猜你喜欢
        • 2017-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-23
        • 2021-10-30
        • 2011-04-27
        相关资源
        最近更新 更多