[英]Input loses focus after typing character React
我已經嘗試調試了幾個小時,並查看了具有相同問題風格的所有其他 Stack Overflow 問題,但他們都只是說要使用密鑰,但這仍然對我不起作用。 我為我的代碼制作了一個更簡單的示例來復制錯誤。
import React from 'react'
import { useState } from 'react'
const FormTest = () => {
const [name, setName] = useState('')
const TestExperience = (props) => {
return (<div>
<h1>Test Experience {props.num}</h1>
<input
type="text"
name="name"
placeholder="Name"
/>
</div>)
}
const processFormData = (event) => {
event.preventDefault();
console.log(event.target);
}
const [nums, setNums] = useState([1, 2, 3]);
const arr = nums.map((num, index) => <TestExperience num={num} key={index}/>);
return (
<div>
<form onSubmit={(event) => {
processFormData(event);
}}>
{arr}
<button onClick={() => {
setNums([...nums, nums.length + 1]);
}}>Add one!</button>
</form>
</div>
)
}
export default FormTest
我已經嘗試將 TestExperience 移到它自己的、單獨的 function 上。 我試圖基本上擁有可以創建更多的輸入,而這個失去焦點的問題來自這樣一個事實,即每次添加輸入時,所有現有的 formData 由於重新渲染而消失。 目標是只使用 onSubmit function 來解析數據,但由於它在添加輸入后消失了,我想我需要存儲它。 一個又一個兔子洞,我一直在嘗試解決看似如此簡單的問題,並且在我嘗試的每一個實現中都遇到問題。
總體目標是我有一個提交按鈕和一個添加輸入按鈕,我試圖放棄整個 value={stateVariable} 和 onChange={setStateVariable} 的東西,只是讓輸入按鈕成為“提交”按鈕,這樣我就可以運行 processFormData 並根據它是哪個提交按鈕做不同的事情,但我不知道如何檢查當有兩個不同按鈕時提交來自哪個按鈕,所以對此的回答也可能非常有幫助,因為那時我可以避免整個 state 混亂。
您需要將TestExperience
移出FormTest
。
import React from "react";
import { useState } from "react";
const TestExperience = (props) => {
const [name, setName] = useState("");
return (
<div>
<h1>Test Experience {props.num}</h1>
<input
type="text"
name="name"
placeholder="Name"
onChange={(event) => {
event.preventDefault();
setName(event.target.value);
}}
value={name}
/>
</div>
);
};
const FormTest = () => {
const processFormData = (event) => {
event.preventDefault();
console.log(event.target);
};
const [nums, setNums] = useState([1, 2, 3]);
const arr = nums.map((num, index) => (
<TestExperience num={num} key={index} />
));
return (
<div>
<form
onSubmit={(event) => {
processFormData(event);
}}
>
{arr}
//another way I tried to do it below //
{nums.map((num, index) => (
<TestExperience num={num} key={index} />
))}
<button
onClick={() => {
setNums([...nums, nums.length + 1]);
}}
>
Add one!
</button>
</form>
</div>
);
};
export default FormTest;
代碼沙箱 => https://codesandbox.io/s/trusting-elbakyan-mxrez?file=/src/App.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.