简体   繁体   English

反应 onChange 不更新状态

[英]React onChange not updating state

I am creating a simple login form and I am saving the users information to state as they type.我正在创建一个简单的登录表单,并且正在保存用户信息以在他们键入时进行说明。 However, the value does not register to state as expected.但是,该值未按预期注册为状态。

Here is the user state这是用户状态

const [user, setUser] = useState({
    firstName: '',
    lastName: '',
    email: ''
});

Here is the input component这是输入组件

export function Input({ id, placeholder, autoComplete, type, name, label, value, handleInputChange }) {
    return (
        <div className="form-input">
            <label className="form-label" htmlFor={id}>{label}</label>
            <input
                placeholder={placeholder}
                autoComplete={autoComplete}
                id={id}
                type={type}
                name={name}
                value={value}
                onChange={handleInputChange}
            />
        </div>
    )
}

Here is the handleInputChange function that is passed into the input component这里是传入输入组件的handleInputChange函数

function handleInputChange(event) {
    const { name, value } = event.target;
    setUser({ ...user, [name]: value });
}

Here is how one of the input components is used in the parent component这是在父组件中使用输入组件之一的方式

<Input
    id="first-name"
    placeholder="Charlie"
    autoComplete="given-name"
    type="text"
    name="firstName"
    label="First Name"
    value={user.firstName}
    handleInputChange={handleInputChange}
 />

Here are some resources I've looked at thus far:以下是我迄今为止看过的一些资源:

I'd suggest to create one state per input field:我建议为每个输入字段创建一个状态:

export function Form({ addItem }) {
    const [name, setName] = useState('');

    return (
        <form>
            <Input
                id="first-name"
                placeholder="Charlie"
                autoComplete="given-name"
                type="text"
                name="firstName"
                label="First Name"
                value={user.firstName}
                handleInputChange={(event) => setName(event.target.value)}
            />
        </form>
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM