React Frontend Selection Implementation Guide

To implement the front-end selection, you can use useRef and useState in React to manage the selection state and use the window.getSelection() method to retrieve selection information.

Firstly, define a ref in the component to store the selection and a state to store the selection status.

import React, { useState, useRef } from 'react';

function App() {
  const [selection, setSelection] = useState(null);
  const textRef = useRef(null);

  // 处理选区变化的函数
  const handleSelectionChange = () => {
    const selectedText = window.getSelection().toString();
    setSelection(selectedText);
  };

  return (
    <div>
      <div ref={textRef} onMouseUp={handleSelectionChange}>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
      </div>
      <p>选中的文本:{selection}</p>
    </div>
  );
}

export default App;

Next, add an onMouseUp event handler to the div element, which will be triggered when the mouse is released. Inside the function, we use window.getSelection().toString() to retrieve the selected text and set it as the selected state.

Finally, render the selected text on the page to achieve front-end selection functionality.

bannerAds