簡體   English   中英

無法清除 textarea 中的文本選擇

[英]Can't clear text selection from textarea

問題:

我有多個textarea可以使用箭頭鍵導航。 textarea使用ref.focus()聚焦。

textarea以這種方式聚焦時,文本選擇不會被清除?

截屏

在此處輸入圖片說明

預計

單擊第一個textarea或再次聚焦第二個textarea時,應清除第二個textarea的文本選擇。

代碼

import React, { useEffect, useRef, useState } from "react";

export const Test = () => {
  const [editingBlock, setEditingBlock] = useState<Number | null>(null);
  const textArea1Ref = useRef<HTMLTextAreaElement | null>(null);
  const textArea2Ref = useRef<HTMLTextAreaElement | null>(null);

  useEffect(() => {
    // set 1 focus
    if (editingBlock === 1 && textArea1Ref.current) {
      textArea1Ref.current.focus();

      // blur 2
      if (textArea2Ref.current) {
        textArea2Ref.current.blur();
      }

      // set 2 focus
    } else if (editingBlock === 2 && textArea2Ref.current) {
      textArea2Ref.current.focus();

      // blur 1
      if (textArea1Ref.current) {
        textArea1Ref.current.blur();
      }
    }
  }, [editingBlock]);

  return (
    <>
      <div>
        <textarea
          ref={textArea1Ref}
          value={"a really long string"}
          onBlur={(e) => setEditingBlock(null)}
          onKeyDown={(e) => {
            if (e.key === "ArrowDown") setEditingBlock(2);
          }}
          onClick={(e) => setEditingBlock(1)}
        />
      </div>
      <div>
        <textarea
          ref={textArea2Ref}
          value={"a really long string"}
          onBlur={(e) => {
            if (window.getSelection()) {
              window.getSelection()!.removeAllRanges(); // doesn't work
            }
            setEditingBlock(null);
          }}
          onClick={(e) => setEditingBlock(2)}
        />
      </div>
    </>
  );
};

值將始終相同

您已使用字符串設置值,這永遠不會改變,因為它是字段中的靜態值。

如果您想讓字段可變,請使用一些狀態、reducer 或庫來處理字段。

這是一個例子

const [textArea1, setTextArea1] = useState<string>('');
...
return (
  ...
  <textarea
     ref={textArea1Ref}
     value={textArea1}
     onChange={(event) => setTextArea1(event.target.value)}
  />
  ...
)

要清除模糊字段,您只需要觸發setTextArea1('')

黑客解決方案

我仍然不完全理解為什么會發生這種情況,但現在找到了一個解決方法:

textareaonBlur回調中,只需使用以下代碼:

if (textArea2Ref.current) {
    // if there's a range selection
    if (textArea2Ref.current.selectionStart !== textArea2Ref.current.selectionEnd) {
        // reset the range
        textArea2Ref.current.selectionStart = textArea2Ref.current.selectionEnd;

        // blur the textarea again, because setting the selection focuses it?
        textArea2Ref.current.blur();
    }
}

暫無
暫無

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

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