gpt4 book ai didi

javascript - 如何在部分输入中创建拆分?

转载 作者:行者123 更新时间:2023-11-28 02:20:47 24 4
gpt4 key购买 nike

我正在尝试创建电话输入,其中每个数字都放置在单独的输入中。至少我是这么想的。

enter image description here

我已经创建了输入并将它们连接到一个数组。数据:常量值 = ['', '', '', ... ]。但问题是我应该以某种方式从输入切换到输入每个字符输入或删除字符。

如何更好地创建这样的输入?

我创建了 codesandbox使用 React。

最佳答案

基本上您可以保存每个输入的引用并调用焦点更改值。这是添加和删除值的完成。

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = () => {
const [value, setValue] = useState(["", "", "", "", "", "", "", "", "", ""]);
const [ref] = useState([null, null, null, null, null, null, null, null, null, null]);

const onChangeValue = (newValue, index) => {
if (newValue.match(/(\d|^(?![\s\S]))/g) && newValue.length <= 2) {
setValue([
...value.slice(0, index),
newValue.slice(-1),
...value.slice(index + 1)
]);
if (newValue.length > 0 && ref[index + 1]) {
ref[index + 1].focus();
}
}
};

const onRemove = (key, index) => {
if (key === "Backspace") {
ref[index - 1].focus();
}
};

return (
<div className="App">
<span>(</span>
<input
ref={input => {
ref[0] = input;
}}
value={value[0]}
onChange={({ target }) => onChangeValue(target.value, 0)}
/>
<input
ref={input => {
ref[1] = input;
}}
value={value[1]}
onChange={({ target }) => onChangeValue(target.value, 1)}
onKeyUp={({ key }) => onRemove(key, 1)}
/>
<input
ref={input => {
ref[2] = input;
}}
value={value[2]}
onChange={({ target }) => onChangeValue(target.value, 2)}
onKeyUp={({ key }) => onRemove(key, 2)}
/>
<span>)</span>
<input
ref={input => {
ref[3] = input;
}}
value={value[3]}
onChange={({ target }) => onChangeValue(target.value, 3)}
onKeyUp={({ key }) => onRemove(key, 3)}
/>
<input
ref={input => {
ref[4] = input;
}}
value={value[4]}
onChange={({ target }) => onChangeValue(target.value, 4)}
onKeyUp={({ key }) => onRemove(key, 4)}
/>
<input
ref={input => {
ref[5] = input;
}}
value={value[5]}
onChange={({ target }) => onChangeValue(target.value, 5)}
onKeyUp={({ key }) => onRemove(key, 5)}
/>
<span>–</span>
<input
ref={input => {
ref[6] = input;
}}
value={value[6]}
onChange={({ target }) => onChangeValue(target.value, 6)}
onKeyUp={({ key }) => onRemove(key, 6)}
/>
<input
ref={input => {
ref[7] = input;
}}
value={value[7]}
onChange={({ target }) => onChangeValue(target.value, 7)}
onKeyUp={({ key }) => onRemove(key, 7)}
/>
<input
ref={input => {
ref[8] = input;
}}
value={value[8]}
onChange={({ target }) => onChangeValue(target.value, 8)}
onKeyUp={({ key }) => onRemove(key, 8)}
/>
<input
ref={input => {
ref[9] = input;
}}
value={value[9]}
onChange={({ target }) => onChangeValue(target.value, 9)}
onKeyUp={({ key }) => onRemove(key, 9)}
/>
</div>
);
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

codesandbox

关于javascript - 如何在部分输入中创建拆分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57809902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com