javascript - 如何在使用参考的反应js中将焦点设置为下一个输入
问题描述
我在地图中使用多个输入,当我在 React Hooks 中单击输入时,我想将焦点设置为下一个输入。在裁判的帮助下
我正在使用材质 ui 文本字段来获取输入
我尝试在没有 ref 的反应类组件中工作,但在钩子中它不能工作类组件代码:
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()
}
};
内部渲染在地图功能中添加了这个
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}`} /> ))
解决方案
您可以转换this.inputRefs
为 React ref,以便它通过渲染持续存在,除此之外,您几乎可以删除对任何this
对象的所有引用。
示例组件:
const LENGTH = 10;
const clamp = (min, max, val) => Math.max(min, Math.min(val, max));
export default function App() {
const [data] = useState([...Array(LENGTH).keys()]);
const inputRefs = useRef([]); // <-- ref to hold input refs
const handleKeyPress = index => () => { // <-- enclose in scope
const nextIndex = clamp(0, data.length - 1, index + 1); // <-- get next index
inputRefs.current[nextIndex].focus(); // <-- get ref and focus
};
return (
<div className="App">
{data.map((data, index) => (
<div key={index}>
<TextField
inputProps={{ onKeyPress: handleKeyPress(index) }} // <-- pass index
inputRef={(ref) => (inputRefs.current[index] = ref)} // <-- save input ref
/>
</div>
))}
</div>
);
}
推荐阅读
- python - 如何将值发送到现有的并在列中覆盖
- content-management-system - Open Journal System 版本降级
- javascript - React Material-UI 在 DataGrid 中添加链接
- angular - Angular Universal - 手动输入 URL 时加载时间长
- android - 如何在新 API 中重新加载奖励广告?
- python - 如何在 Python 中对名称实体识别 (NER) 模型和 pyspark 的实现代码进行单元测试?
- css - @font face,调用字体系列适用于一个类,但不适用于另一个类,为什么?
- flutter - 使用http包中的get方法时Flutter抛出错误
- python - 将 GPT-2 转换为 ONNX 和 TF.js 后,TF SavedModel 具有固定的输入大小
- javascript - 我们如何在 Laravel 中嵌入“文本编辑器”(任何编辑器),这将帮助我们一次存储多个图像