Implement a function to copy the text content in the input box

1. Scene

Sometimes, some projects need to display some data in the form, but these data are not allowed to be edited, but we may also need to use the data in the input box in other places. In order to better improve the user experience, at this time a The ability to copy the text content in this box is particularly important. The effect is as follows:Insert image description here

Insert image description here

2. How to achieve

We know that the basic usage of ref is to obtain DOM elements, so we can use ref to obtain the DOM element we want to operate. The code is as follows:

1. First declare the ref type inputRef
const inputRef = useRef<any>(null) //ts类型的声明
const inputRef = useRef()  //js类型的声明
2. Get DOM elements through ref
 <Form.Item
                label="推送接口"
                name="sendInterface"
                className="api-form"
              >
                <Input
                  ref={
    
    inputRef}
                  disabled={
    
    true}
                  className="sendInterface"
                  addonAfter={
    
    
                    <a onClick={
    
    handleCopyClick}>
                      <AiIcon
                        type="#iconcopy"
                        color="#666666"
                        width={
    
    16}
                        height={
    
    16}
                        style={
    
    {
    
     margin: '0 2px' }}
                      />
                    </a>
                  }
                />
              </Form.Item>
3. Register the click event, obtain the copied content through an execCommand method provided by the document object, and then prompt the copying success throughmessage.success.
message needs to be introduced first, as follows:
import {
    
    
  message,
} from 'antd';
const handleCopyClick = () => {
    
    
    //在选择节点的时候,一定要只选择input
    var copyDOM = document.querySelector('.sendInterface') //需要复制文字的节点
    var range = document.createRange() //创建一个range
    window.getSelection().removeAllRanges() //清楚页面中已有的selection
    range.selectNode(copyDOM) // 选中需要复制的节点
    window.getSelection().addRange(range) // 执行选中元素
    var successful = document.execCommand('copy') // 执行 copy 操作
    if (successful) {
    
    
      message.success('复制成功!')
    } else {
    
    
      message.warning('复制失败!')
    }
    // 移除选中的元素
    window.getSelection().removeAllRanges()
  }

Guess you like

Origin blog.csdn.net/m0_46412825/article/details/121349430