簡體   English   中英

選擇文本並突出顯示選擇或獲取選擇值(反應)

[英]Select Text & highlight selection or get selection value (React)

我有一個顯示一些跨度的 React 應用程序:

<span>Hello</span> <span>my</span> <span>name</span> <span> is </span> ...

我希望用戶像這樣用鼠標選擇文本你好我的名字是

..然后獲取選定的值,或突出顯示文本等。我​​將如何在 React 中執行此操作? 我不確定要使用什么事件處理程序以及如何獲取當前選擇! 一個最小的例子或提示將不勝感激!

使用onMouseUponDoubleClick事件來檢測調用方法,這將使用 JavaScript Selection API 確定選擇。

使用window.getSelection()獲取選擇對象。

要獲取選定的文本,請使用window.getSelection.toString()

要獲取用於呈現彈出菜單的選定文本區域的坐標,請使用selection.getRangeAt(0).getBoundingClientRect()

作為示例實現,請查看react-highlight庫。

對此沒有 React 特定的解決方案。 只需使用window.getSelection API。


要輸出突出顯示的文本,請運行window.getSelection().toString()

我認為這是正確的方法...

 document.onmouseup = () => {
   console.log(window.getSelection().toString());
 };

這是 React 中使用函數式組件的示例:

const Post = () => {
    const handleMouseUp() {
        console.log(`Selected text: ${window.getSelection().toString()}`);
    }
    return (
        <div onMouseUp={handleMouseUp}>Text</div>
    );
}

正如 Lyubomir 指出的,window.getSelection() API 可以解決問題!

第 1 步: - 最初每次輸入內容時,鼠標都會捕獲

<textarea type="text" 
          className="contentarea__form__input" 
          onMouseUpCapture={this.selectedText}>
</textarea>

第 2 步:為了確保它只捕獲您選擇的文本,我使用了 if-else 條件

selectedText = () => {
    window.getSelection().toString() ? console.log(window.getSelection().toString()) : null;
}

由於Firefox 中的這個錯誤,我無法按照其他答案的建議使用window.getSelection()

所以我必須執行以下操作(在 React 中):

constructor(props) {
    this.textAreaRef = React.createRef();
}

getSelection() {
    const textArea = (this.textAreaRef.current as HTMLTextAreaElement);
    console.log(textArea.value.substring(
            textArea.selectionStart,
            textArea.selectionEnd
        )
    );
}

render() {
    <textarea onMouseUp={() => this.getSelection()}
                        ref={this.textAreaRef}>
    </textarea>
}

我剛剛為此做了一個自定義鈎子(如果需要,在打字稿中):


    export const useSelectedText = () => {
        const [text, setText] = useState('')
        const select = () => {
            const selected = window.getSelection() as Selection
            setText(selected.toString())
        }
        return [select, text] as const
    }

這可以使用react-text-annotate庫來完成: https : //www.npmjs.com/package/react-text-annotate

我們可以簡單地使用 state 來選擇和突出顯示它們。

import styled from 'styled-components';

const ClipBoardLink = styled.span<{ selection: boolean }>`
  background: ${(p) => (p.selection ? '#1597E5' : '')};
  margin-left: 0.5rem;
  color: ${(p) => (p.selection ? '#fff' : '')};
`;

const GroupOrderModel = () => {
  const [isCopied, setIsCopied] = useState(false);

  const handleIsClipboardCopy = async (text: string) => {
    setIsCopied(true);

    navigator.clipboard.writeText(text);

    setTimeout(() => {
      setIsCopied(false);
    }, 5000);
  };

  return (
      <ClipBoardLink selection={isCopied} onClick={async () => await handleIsClipboardCopy("Click me!")}>Click me!</ClipBoardLink>
   );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM