首页 > 解决方案 > 使用“Ctrl+A”全选并删除输入字段的内容

问题描述

我正在为社会安全号码创建一个输入字段,但输入字段的功能存在问题。我希望能够在 Mac 上按“Ctrl + A”或“Command + A”来选择输入字段的内容,然后将其删除。我无法在带有 Chrome 的 Windows 10 上执行此操作。关于修改什么以允许这种行为的任何想法?

这是一个代码框:https ://codesandbox.io/s/tel-formating-forked-3uz9q?file=/src/App.js

这是相关的代码:

//App.js

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

export default function App() {
  const [state, setState] = useState({ phone: "" });
  const cursorPos = useRef(null);
  const inputRef = useRef(null);
  const keyIsDelete = useRef(false);

  const handleChange = (e) => {
    cursorPos.current = e.target.selectionStart;
    let val = e.target.value;
    cursorPos.current -= (
      val.slice(0, cursorPos.current).match(/-/g) || []
    ).length;
    let r = /(\D+)/g,
      first3 = "",
      next3 = "",
      last4 = "";
    val = val.replace(r, "");
    let newValue;
    if (val.length > 0) {
      first3 = val.substr(0, 3);
      next3 = val.substr(3, 2);
      last4 = val.substr(5, 4);
      if (val.length > 5) {
        newValue = first3 + "-" + next3 + "-" + last4;
      } else if (val.length > 3) {
        newValue = first3 + "-" + next3;
      } else if (val.length < 4) {
        newValue = first3;
      }
    } else newValue = val;
    setState({ phone: newValue });
    for (let i = 0; i < cursorPos.current; ++i) {
      if (newValue[i] === "-") {
        ++cursorPos.current;
      }
    }
    if (newValue[cursorPos.current] === "-" && keyIsDelete.current) {
      cursorPos.current++;
    }
  };

  const handleKeyDown = (e) => {
    const allowedKeys = [
      "Control",
      "Delete",
      "ArrowLeft",
      "ArrowRight",
      "Backspace",
      "Home",
      "End",
      "Enter",
      "Tab"
    ];
    if (e.key === "Delete") {
      keyIsDelete.current = true;
    } else {
      keyIsDelete.current = false;
    }
    if ("0123456789".includes(e.key) || allowedKeys.includes(e.key)) {
    } else {
      e.preventDefault();
    }
  };

  useLayoutEffect(() => {
    if (inputRef.current) {
      inputRef.current.selectionStart = cursorPos.current;
      inputRef.current.selectionEnd = cursorPos.current;
    }
  });

  return (
    <div className="App">
      <input
        ref={inputRef}
        type="text"
        value={state.phone}
        placeholder="SSN"
        onChange={handleChange}
        onKeyDown={handleKeyDown}
      />
    </div>
  );
}

标签: javascriptreactjs

解决方案


您需要为 mac 添加“Meta”(而不是 control)和“a”来检测在按 control 到 allowedKeys 数组后实际发生的情况。问题是即使控制也不允许“a”键本身。

 const allowedKeys = [
      "Control",
      "Delete",
      "ArrowLeft",
      "ArrowRight",
      "Backspace",
      "Home",
      "End",
      "Enter",
      "Tab",
      "Meta",
      "a"
    ];

推荐阅读