gpt4 book ai didi

javascript - 如何将焦点设置到下一个输入上的输入键按下 react js与refs

转载 作者:行者123 更新时间:2023-12-04 14:56:56 25 4
gpt4 key购买 nike

我在 map 中使用多个输入,当我在 React Hooks 中单击输入时,我想将焦点设置为下一个输入。
在裁判的帮助下
我正在使用 Material ui 文本字段来获取输入
我尝试在没有 ref 的 react 类组件中工作,但在钩子(Hook)中它不起作用
类组件代码:

constructor(props) {
this.state = {}
}
inputRefs = [];
 _handleKeyPress = e => {
const {currentTarget} = e;
let inputindex = this.inputRefs.indexOf(currentTarget)
if (inputindex < this.inputRefs.length - 1) {
this.inputRefs[inputindex + 1].focus()
}
else {
this.inputRefs[0].focus()
}
};
内部渲染在 map 功能中添加了这个
this.state.data.map((data) => return (
<TextField
inputProps = {{onKeyPress:(e) => this.function1(e, data)}}
onChange={this.changevaluefunction}
inputRef={ref => this.inputRefs.push(ref)}
onFocus={this.handleFocus} ref={`input${id}`} /> ))

最佳答案

我用功能组件以不同的方式实现了解决方案。我已经选择了 4 个字段,并用 createRef 设置了它的引用。钩。
我可以从您的解决方案中看到,您希望在按下 Enter 时将焦点移至下一个输入元素键在当前元素上。
我在 onKeyUp 中传递下一个目标元素参数处理程序连同实际事件,然后检测是否 Enter键是否按下。如果 Enter键被按下,targetElem存在然后我将焦点转移到通过的targetElem .通过这种方式,您可以更好地控制输入。
你可以在这里看到我的解决方案
https://codesandbox.io/s/friendly-leftpad-2nx91?file=/src/App.js

import React, { useRef } from "react";
import TextField from "@material-ui/core/TextField";
import "./styles.css";

const inputs = [
{
id: "fName",
label: "First Name"
},
{
id: "lName",
label: "Last Name"
},
{
id: "gender",
label: "Gender"
},
{
id: "address",
label: "Address"
}
];

export default function App() {
const myRefs = useRef([]);

const handleKeyUp = (e, targetElem) => {
if (e.key === "Enter" && targetElem) {
targetElem.focus();
}
};

return (
<div>
{inputs.map((ipt, i) => (
<TextField
onKeyUp={(e) =>
handleKeyUp(e, myRefs.current[i === inputs.length - 1 ? 0 : i + 1])
}
inputRef={(el) => (myRefs.current[i] = el)}
id={ipt.id}
fullWidth
style={{ marginBottom: 20 }}
label={ipt.label}
variant="outlined"
key={ipt.id}
/>
))}
</div>
);
}

关于javascript - 如何将焦点设置到下一个输入上的输入键按下 react js与refs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67782669/

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