简体   繁体   中英

Uncontrolled input React Hooks

I've started learing about react-hooks with a simple tutorial and to my surprise I got an error that I cannot figure out:

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.

After this error, my component disappears but I still can input data that will correctly print out in console.

I've tried setting initial state for inputs and changing

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

to

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

but I'm still getting error.

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;


Hooks

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;

Any ideas what causes this error?

You are getting the error, because your inputs start their life as undefined and then have a value. If you declare your object in const [inputs, setInputs] = useState({}); it will go away.

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

my favorite way of handling controlled inputs in react hooks is this syntax.. Make seperate state for each input you are trying to handle and then inside the onChange just call the setInput

onChange={e => setInput(e.target.value)}

the reason why you have an error is because the initial state is just an empty object, if you wanted to do it that way you would have to change your state to.

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

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