javascript 如何获取React中onCopy事件的复制值?

3lxsmp7m  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(173)

假设我有一个长字符串:

"Jackie has a very big chicken at his farm"

突出显示字符串中的“chicken”并按ctrl+C,
它将触发handleCopy函数,该函数传递到元素的onCopy属性中。我希望复制子字符串或字符串的值,在本例中为“chicken”。例如,

function handleCopy(event){
     //get the copied value here
}

<input value="Jackie has a very big chicken at his farm" onCopy={handleCopy} />

我如何能够在React中实现这一点?

zengzsys

zengzsys1#

您可以对它使用copy eventgetSelection方法,如docs示例所示...

    • 示例如下**
const App = () => {
  function handleCopy(event) {
    const selection = document.getSelection();
    console.log(selection.toString())
  }
  return (
    <input
      defaultValue="Jackie has a very big chicken at his farm"
      onCopy={handleCopy}
    />
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

相关问题