在 React.useState 中保存对象



我的 react 项目中有一个表单,我希望每个字段的值都存储在状态中。 与其每个字段有多个状态,不如如何将表单值存储为状态中的对象?更重要的是,我如何访问它?(带反应钩子(

import React from 'react';
export const UserData = () => {
return(
<form>
<input type="text" placeholder="Name" />
<input type="email" placeholder="Email" />
<button>Confirm</button>
</form>
)
}

React Hooks 允许您使用 useState 定义 JavaScript 对象。看 https://daveceddia.com/usestate-hook-examples/

function LoginForm() {
const [form, setState] = useState({
username: '',
password: ''
});

使用函数更新表单:

const updateField = e => {
setState({
...form,
[e.target.name]: e.target.value
}); 
};

调用函数 on提交按钮

<form onSubmit={updateField}>
<input type="text" placeholder="Name" />
<input type="email" placeholder="Email" />
<Button >Confirm</button>
</form>

您可以使用useState钩子。检查这个

const [state, setState] = useState({ name, email });

在基于类的组件中设置类似于setState的状态:

setState({name: 'react', email: 'react'})    

访问状态值:

import React, { useState } from 'react';
export const UserData = () => {
const [state, setState] = useState({ name, email });
return(
<form>
<input type="text" placeholder="Name" value={state.name} />
<input type="email" placeholder="Email" value={state.email}  />
<button>Confirm</button>
</form>
)
}

如果要使用useState将表单值存储为对象,则应创建一个初始状态值,以便在出现错误后回滚到初始状态。例

const initialState = {
name: "",
email: ""
};
export const UserData = () => {
const [formState, setFormState] = useState(initialState);
const submitHandler = event => {
event.preventDefault();
console.log(formState);
};
return (
<form onSubmit={submitHandler}>
<input
type="text"
placeholder="Name"
value={formState.name}
onChange={e => {
setFormState({ ...formState, name: e.target.value });
}}
/>
<input
type="email"
placeholder="Email"
value={formState.email}
onChange={e => {
setFormState({ ...formState, email: e.target.value });
}}
/>
<button>Confirm</button>
</form>
);
};

代码沙箱中的工作演示。

相关内容

  • 没有找到相关文章

最新更新