【发布时间】:2021-04-09 19:09:58
【问题描述】:
我正在尝试在 URL 缩短后从 div 复制文本。
我在div 中放置了一个ref 值,它将呈现缩短的URL。但是,我收到错误:
TypeError: inputArea.input.select() 不是函数。
我不确定如何引用 div 中的文本。
import { useCallback, useEffect, useRef, useState } from "react";
const Shorten = () => {
const [copySuccess, setCopySuccess] = useState('');
const inputArea = useRef(null);
function copyLink(e){
inputArea.current.select();
document.execCommand('copy');
e.target.focus();
setCopySuccess('Copied!');
};
{isPending && <div className="loading-text">Loading...</div>}
{shortLink && <div ref={inputArea} className="shorten-text">{shortLink}</div>}
<hr></hr>
<div>
<button className="shorten-it" onClick={copyLink} >Copy</button>
{copySuccess}
</div>
</section>
【问题讨论】:
-
select函数仅适用于input或textarea元素。它不适用于div。见this answer。
标签: javascript reactjs use-ref