![](/img/trans.png)
[英]Textfield is not allowing me to enter characters on keypress in Firefox
[英]Ability to enter tab characters in a TextField?
我有一個定義為多行的 MUI TextField
。 我的目標是輸入 JSON 文本。 我發現當我按下 Tab 鍵時,我的組件失去了焦點,焦點被轉移到了屏幕上的下一個組件。 我想要的是將制表符值 (\\t) 輸入到字符串文本中。 是否有禁用 Tab 鍵作為導航工具的方法?
默認情況下,如果您在input
字段中按Tab ,瀏覽器會將焦點切換到下一個元素。 要覆蓋該行為,您可以監聽keydown
事件並調用e.preventDefault()
,然后添加一些代碼以在光標位置插入制表符。 下面是實現。 請注意,由於您正在篡改輸入value
,因此撤消功能不再起作用:
<TextField
multiline
onKeyDown={(e) => {
const { value } = e.target;
if (e.key === 'Tab') {
e.preventDefault();
const cursorPosition = e.target.selectionStart;
const cursorEndPosition = e.target.selectionEnd;
const tab = '\t';
e.target.value =
value.substring(0, cursorPosition) +
tab +
value.substring(cursorEndPosition);
// if you modify the value programmatically, the cursor is moved
// to the end of the value, we need to reset it to the correct
// position again
e.target.selectionStart = cursorPosition + 1;
e.target.selectionEnd = cursorPosition + 1;
}
}}
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.