英文:
react js Input fields not updating after successful array update
问题
我有一组输入字段,由一个数组动态生成,本来应该默认填充为'?'。一旦用户在其中一个输入字段中输入一个字母,onchange
事件应该触发,并成功更新数组,重新填充输入字段的值。目前,如果我提供一个value={letter}
作为属性,输入字段将如预期地填充,但填充输入字段的数组不会更新。如果我去掉value={letter}
,数组会如预期地更新,但输入字段当然不会填充。
const [letters, setLetters] = useState(workLetters);
function inputChangeHandler(event) {
const incomingLetter = event.target.value;
const nextLetters = [...letters];
letters.forEach((letter, idx) => {
if (letters_rec_of_truth[idx] === incomingLetter) {
nextLetters[idx] = incomingLetter;
}
});
console.log("next letters is now " + nextLetters);
setLetters(nextLetters);
}
useEffect(() => {}, [letters]);
console.log("letters is now " + letters);
return (
<div>
{letters.map((letter, idx) => {
return (
<input
type="text"
key={idx}
value={letter}
onChange={inputChangeHandler}
></input>
);
})}
</div>
);
英文:
I have a set of a input fields, dynamically generated by an array that are intended to be populated by default with a '?'. Once a user enters a letter into one of the inputs, the onchange
event should fire and the array updates successfully, repopulating the inputs with the updated values. As of now, if I provide a value={letter}
as an attribute, the inputs populate as expected, but the array that populates the inputs does not update. If I take value={letter}
out, the array updates as expected, but the inputs of course, don't populate.
const [letters, setLetters] = useState(workLetters);
function inputChangeHandler(event) {
const incomingLetter = event.target.value;
const nextLetters = [...letters];
letters.forEach((letter, idx) => {
if (letters_rec_of_truth[idx] === incomingLetter) {
nextLetters[idx] = incomingLetter;
}
});
console.log("next letters is now " + nextLetters);
setLetters(nextLetters);
}
useEffect(() => {}, [letters]);
console.log("letters is now " + letters);
// console.log(evt);
return (
<div>
{letters.map((letter, idx) => {
return (
<input
type="text"
key={idx}
value={letter}
onChange={inputChangeHandler}
></input>
);
})}
</div>
);
答案1
得分: 0
为什么不使用'默认值'而使用'输入'标签的值?
英文:
Why instead of 'value' dont you use 'defaultValue' for the 'input' tag?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论