使用 ReactJS 自动选择跨度标签

IT技术 javascript html reactjs
2021-05-04 03:45:44

我希望在 span 元素中自动选择一些文本,以便用户可以轻松地复制它。

.select()但是,我尝试过使用,这似乎仅适用于<input>&<textarea>元素;我的文本在 a 内<span>,我不想更改它,因为我使用另一个处理样式的组件处理应用程序中的所有文本(回答@dandavis,因为评论对我不起作用)。

我的文本呈现在弹出窗口中,因此我想为用户显示选定的内容。

这是我尝试过的:

import React from "react";
const PropTypes = React.PropTypes;

class CopyText extends React.Component {
    constructor(props) {
        super(props);
        this.handleRef = this.handleRef.bind(this);
    }

    componentDidUpdate() {
        this.copyText.select();
    }

    handleRef(component) {
        this.copyText = component;
    }

    render() {
        return (
            <span ref={this.handleRef}>
                {this.props.text}
            </span>
        );
    }
}

CopyText.propTypes = {
    text: PropTypes.string
};

export default CopyText;

有人能帮我为 span 元素创建一个自定义的自动选择文本功能吗?非常感谢您的建议。

1个回答

你可以试试这个

<span ref={textAreaRef}>your text</span>
<Button type="button" onClick={() => copyEmail()}>copy</Button>

和复制功能应该是这样的:

const copyEmail = () => {
    let currentNode = textAreaRef.current;
    if (document.body.createTextRange) {
        const range = document.body.createTextRange();
        range.moveToElementText(currentNode);
        range.select();
        document.execCommand('copy');
        range.remove();
    } else if (window.getSelection) {
        const selection = window.getSelection();
        const range = document.createRange();
        range.selectNodeContents(currentNode);
        selection.removeAllRanges();
        selection.addRange(range);
        document.execCommand('copy');
        selection.removeAllRanges();
    } else {
        alert("Could not select text, Unsupported browser");
    }
}

这会起作用我已经使用 useRef 创建了一个 ref

const textAreaRef = useRef(null);