useState 更新 React 中的多个值 [英] useState to update multiple values in React

查看:24
本文介绍了useState 更新 React 中的多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用钩子在 React 组件中收集了一系列用户数据元素.

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

const [mobile, setMobile] = useState('');
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');

更新如下.

<input type="text"
       className="form-control"
       id="mobile"
       placeholder="Enter a valid mobile number"
       onChange={event => {setMobile(event.target.value)}}/>

是否有更简洁的方法来使用对象作为变量?

Is there a more succint way to do this using an object as the variable?

推荐答案

您应该将 name 属性添加到输入标签.每个名称都必须引用 AllValues 对象中的键.

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}
   />
   // ...
)

这篇关于useState 更新 React 中的多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆