我有多个textarea
,可以使用箭头键进行导航。 textarea
使用ref.focus()
进行聚焦。
以这种方式聚焦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>
</>
);
};
中的文本选择。
{
答案 0 :(得分:0)
您已使用字符串设置了值,由于它是字段中的静态值,因此它永远不会改变。
如果您想使字段可变,请使用某种状态,reducer或库来处理字段。
这是一个例子
const [textArea1, setTextArea1] = useState<string>('');
...
return (
...
<textarea
ref={textArea1Ref}
value={textArea1}
onChange={(event) => setTextArea1(event.target.value)}
/>
...
)
要清除模糊区域,您只需开火setTextArea1('')
。
答案 1 :(得分:0)
我仍然不完全了解为什么会发生这种情况,但是现在找到了一种解决方法:
在textarea
的{{1}}回调中,只需使用以下代码:
onBlur