简体   繁体   中英

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

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>
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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