使用ReactJS自动选择范围标记

问题描述 投票:1回答:1

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

我尝试使用.select(),但这似乎仅适用于<input><textarea>元素;我的文本在<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元素创建自定义自动选择文本功能吗?非常感谢您的建议。

我希望自动在span元素中选择一些文本,以便用户可以轻松地复制它。我尝试使用.select(),但这似乎仅对

javascript html reactjs
1个回答
0
投票

您可以尝试这个

<span ref={textAreaRef}>your text</span>
<Button type="button" onClick={() => copyEmail()}>copy</Button>
© www.soinside.com 2019 - 2024. All rights reserved.