gpt4 book ai didi

javascript - 不受控制的输入 React Hooks

转载 作者:搜寻专家 更新时间:2023-10-31 22:10:19 25 4
gpt4 key购买 nike

我已经开始使用 simple tutorial 学习 react-hooks令我惊讶的是,我遇到了一个我无法弄清楚的错误:

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

发生此错误后,我的组件消失了,但我仍然可以输入将在控制台中正确打印的数据。

我试过为输入设置初始状态并更改

setInputs(inputs => ({
...inputs, [event.target.name]: event.target.value
}));

setInputs({...inputs, [event.target.name]: event.target.value});

但我仍然遇到错误。

JSX

import React from 'react';
import './styles/form.scss';
import useSignUpForm from './hooks/customHooks.jsx';

const Form = () => {

const {inputs, handleInputChange, handleSubmit} = useSignUpForm();

return (
<React.Fragment>
<div className="formWrapper">
<h1 className="header">Form</h1>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="nicknameInput">Nickname</label>
<input type="text" id="nicknameInput" name="nickname" onChange={handleInputChange}
value={inputs.nickname} required/>

<label htmlFor="emailInput">Email Address</label>
<input type="text" id="emailInput" name="email" onChange={handleInputChange}
value={inputs.email} required/>

<label htmlFor="lastName">Last Name</label>
<input type="text" id="lastName" name="lastName" onChange={handleInputChange}
value={inputs.lastName} required/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</React.Fragment>
)
};

export default Form;


钩子(Hook)

import React, {useState} from 'react';

const useSignUpForm = (callback) => {
const [inputs, setInputs] = useState({});
console.log(inputs);

const handleSubmit = (event) => {
if (event) {
event.preventDefault();
}
};

const handleInputChange = (event) => {
event.persist();
setInputs(inputs => ({
...inputs, [event.target.name]: event.target.value
})
);
};

return {
handleSubmit,
handleInputChange,
inputs
};

};

export default useSignUpForm;

知道导致此错误的原因吗?

最佳答案

您收到错误,因为您的输入以 undefined 开始,然后有一个值。如果将此 const [inputs, setInputs] = useState({}); 替换为:

const [inputs, setInputs] = useState({
nickname: '',
lastname: '',
email: ''
});

它会消失。

关于javascript - 不受控制的输入 React Hooks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56482774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com