【发布时间】:2020-09-14 14:09:53
【问题描述】:
当您点击输入时,将创建一个新字段,但问题是 focus 并且焦点将移至新创建的字段,但问题是:它离开 an enter space in the previous 字段
`
import React, { useState } from "react";
import "./styles.css";
export default function App() {
let elements = [
{ id: 0, text: "first", autoFocus: true },
{ id: 1, text: "second", autoFocus: true },
{ id: 2, text: "third", autoFocus: true }
];
const [state, setstate] = useState(elements);
function handChange(e) {
if (e.keyCode == 13) {
const index = state.findIndex((item) => item.id == e.target.id);
//i'm using autoFocus to move the focus (I-beam pointer) to the nex field.
//but i still get errors with it
Object.assign(state, (state[index].autoFocus = false));
setstate((pre) => {
return [
...pre.slice(0, index + 1),
{ id: 3, text: "xxx", autoFocus: true },
...pre.slice(index + 1, state.length)
];
});
setTimeout(() => {
document.getElementById(index + 1).focus();
}, 0);
}
}
return (
<div className="App">
{state.map((e) => (
<div contentEditable="true" id={e.id} onKeyUp={handChange}>
{e.text}
</div>
))}
</div>
);
}
【问题讨论】:
标签: javascript reactjs react-hooks focus