useState to update multiple values in React

前端 未结 2 1970
自闭症患者
自闭症患者 2021-02-14 07:23

I\'ve a series of user data elements which I\'m collecting inside a React component using hooks.

const [mobile, setMobile] = useState(\'\');
const [username, set         


        
相关标签:
2条回答
  • You should add name attributes to input tags. Each name must refer to key in AllValues object.

    const [allValues, setAllValues] = useState({
       mobile: '',
       username: '',
       email: '',
       password: '',
       confirmPassword: ''
    });
    const changeHandler = e => {
       setAllValues({...allValues, [e.target.name]: e.target.value})
    }
    return (
       <input type="text"
           className="form-control"
           id="mobile"
           name="mobile"
           placeholder="Enter a valid mobile number"
           onChange={changeHandler}
       />
       // ...
    )
    
    0 讨论(0)
  • 2021-02-14 07:49

    The above answer could create issues in some cases, the following should be the right approach.

    const [allValues, setAllValues] = useState({
       mobile: '',
       username: '',
       email: '',
       password: '',
       confirmPassword: ''
    });
    const changeHandler = e => {
       setAllValues( prevValues => {
       return { ...prevValues,[e.target.name]: e.target.value}
    }
    }
    
    0 讨论(0)
提交回复
热议问题