【发布时间】:2022-01-09 07:50:27
【问题描述】:
代码如下:
const [expression, setExpression] = useState("");
const Remove = () => {
const input = document.getElementById("input");
if (expression.length > 0) {
const pos = input.selectionStart;
if (pos > 0) {
setExpression(expression.substring(0, pos - 1) + expression.substring(pos));
input.focus();
input.selectionStart = pos - 1;
input.selectionEnd = pos - 1;
}
}
}
return (
<>
<input id="input" value={expression} />
<button onClick={Remove}>remove</button>
</>
)
我想在单击按钮时删除光标位于输入框中的文本,但在删除数字后光标在输入文本的末尾一次又一次地移动。我希望它保持在输入字段中的位置,而不是放在输入框文本的末尾。
【问题讨论】: