useState to update multiple values in React

前端 未结 2 1974
自闭症患者
自闭症患者 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条回答
  •  时光说笑
    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}
    }
    }
    

提交回复
热议问题