【问题标题】:Reactjs: Input mask after state.length === 5Reactjs:state.length === 5 之后的输入掩码
【发布时间】:2021-01-17 21:11:33
【问题描述】:

我想在输入 5 个这样的字符后添加 - 字符:

但我明白了:

我的代码:

interface IAddress {
  bairro: string;
  cep: string;
  cidade: string;
  complemento: string;
  rua: string;
  numero: string;
}
export default function App() {
  const [address, setAddress] = useState<IAddress>({
    bairro: "",
    cep: "",
    cidade: "",
    complemento: "",
    rua: "",
    numero: ""
  });
  const handlerCep = (e: any) => {
    const { value } = e.target;
    const cep = value.replace(/[^0-9]/g, "");
    setAddress({
      ...address,
      cep: address.cep.length === 5 ? `${cep}-` : cep
    });
  };
  return (
    <div className="App">
      <input
        type="tel"
        maxLength={9}
        value={address.cep}
        onChange={(e) => handlerCep(e)}
        //  onBlur={(ev) => findCep(ev)}
        required
        id="cep"
      />
    </div>
  );
}

我在某些时候吓坏了,我无法想象我该如何解决这个问题 现场示例:

代码沙箱:https://codesandbox.io/s/silly-sea-o4gd5?file=/src/App.tsx

【问题讨论】:

标签: html reactjs


【解决方案1】:

您的代码中存在一些问题,首先您的正则表达式清除了线上的“-”符号:

// update regexp to allow '-'
const cep = value.replace(/[^0-9\-]/g, "")

second - 您正在检查状态中属性的长度,而不是 cep const 变量。状态尚未更新,因此您应该有兴趣从 onchange 事件中检查值的长度并使用计算值更新状态

setAddress({
      ...address,
      // use cep in length check instead of address.cep
      cep: cep.length === 5 ? `${cep}-` : cep
    });

解决上述问题后 - 您应该会看到输入已按预期更新。要考虑的第三个问题 - 删除字符的情况,我想它不会在当前代码中顺利运行。

【讨论】:

  • 嗨,你能帮我用正则表达式不替换“-”吗?
  • 就像我发现了一个问题,我可以使用 9 个“-”我可以分组吗?有 5 个数字 1 - 和 3 个数字的组?
猜你喜欢
  • 1970-01-01
  • 2020-08-15
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
  • 2018-08-13
  • 1970-01-01
相关资源
最近更新 更多