好的,我在 React 中创建了一个相当大的表单(这里只显示了三个字段),因此想要使用自定义钩子进行处理。我发现一篇文章解释了一种方法,但是,当我尝试在我的输入字段中键入文本时,它们不会被填充。我的 e.target 值的 console.log 看起来该字段在每次击键后都会重置。我想念什么?干杯
我试图简化我的代码,并希望它有意义:
import React, { useState } from "react";
//various other imports not relevant for this issue
const NetworkConfig = () => {
//Custom Hook inserted here for easy overview. Normally imported from external file
function useFormFields(initialState) {
const [fields, setValues] = useState(initialState);
return [
fields,
(e) => {
setValues({
...fields,
[e.target.id]: e.target.value,
});
},
];
}
const [fields, handleFieldChange] = useFormFields({
apnValue: "",
apnUsernameValue: "",
apnUserPwdValue: "",
});
// I omitted the submit button and its functionality in this post,
// to keep my problem clear
// The TextField component basicaly just adds some functionality not
// relevant to this problem. It is tested in other scenarios so in this
// case it basically just works as a normal HTML input[type="text"] field
return (
<div>
<div className="network-config-modal" id="network-config">
<div>
<div>
<h2>Network Config</h2>
</div>
<div className="network-config-row">
<div className="network-config-col">
<h3>Cellular Settings</h3>
<section className="network-config-section">
<TextField
value={fields.apnValue}
onChange={handleFieldChange}
label="APN"
outerLabel={true}
light={true}
type="text"
name="apn"
id="apn"
/>
<TextField
onChange={handleFieldChange}
value={fields.apnUsernameValue}
label="APN Username"
optional={true}
outerLabel={true}
light={true}
name="apn-username"
id="apn-username"
/>
<TextField
onChange={handleFieldChange}
value={fields.apnUserPwdValue}
label="APN Password"
optional={true}
outerLabel={true}
light={true}
name="apn-password"
id="apn-pwd"
/>
</section>
</div>
</div>
</div>
</div>
</div>
);
};
export default NetworkConfig;