简体   繁体   English

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

[英]How do I get the copied value on onCopy event in React?

Suppose I have a long string:假设我有一个长字符串:

"Jackie has a very big chicken at his farm"

And I highlight "chicken" from the string and hit ctrl+C,然后我从字符串中突出显示“chicken”并按下 ctrl+C,

It will trigger the handleCopy function passed into onCopy attribute of the element.它将触发传递给元素的onCopy属性的handleCopy函数。 I want to have the value of the substring or string being copied, in this case, "chicken" For example,我想要被复制的子字符串或字符串的值,在本例中为“chicken” 例如,

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

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

How am I able to achieve this in React?我怎样才能在 React 中实现这一点?

Use copy will only trigger the on copy event but will not give you the value. Use copy 只会触发 on copy 事件,但不会给你值。 You can use the useRef hook to get the value.您可以使用 useRef 钩子来获取值。 Please refer the code below.请参考下面的代码。

function App() {
  const inputRef = useRef();
  function handleCopy(event) {
    console.log("copied value :", inputRef.current.value);
  }
  return (
    <div className="App">
      <input
        ref={inputRef}
        value="Jackie has a very big chicken at his farm"
        onCopy={handleCopy}
      />
    </div>
  );
}

Code Sandbox: https://codesandbox.io/s/stoic-robinson-dqmm8p?file=/src/App.js:70-395代码沙箱: https ://codesandbox.io/s/stoic-robinson-dqmm8p?file=/src/App.js:70-395

You can use copy event and the getSelection method on it as shown in the docs example...您可以在其上使用复制事件getSelection方法,如文档示例所示...

A sample eg below下面的示例

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM