Reactjs 通过React useState()处理表单数据的更好方法?
只是想知道是否有人有更好的解决方案来停止我代码中的重复?我目前正在使用Reactjs 通过React useState()处理表单数据的更好方法?,reactjs,typescript,ionic-framework,react-hooks,Reactjs,Typescript,Ionic Framework,React Hooks,只是想知道是否有人有更好的解决方案来停止我代码中的重复?我目前正在使用useState()来处理用户数据,这是相当重复的,因为有大量不同的字段。下面是我的代码: const [lname, setLast] = useState<string>(""); const [country, setCountry] = useState<string>(""); const [phone, setPhone] = useState<
useState()
来处理用户数据,这是相当重复的,因为有大量不同的字段。下面是我的代码:
const [lname, setLast] = useState<string>("");
const [country, setCountry] = useState<string>("");
const [phone, setPhone] = useState<string>("");
const [email, setUsername] = useState<string>("");
const [username, setEmail] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [cpassword, setCPassword] = useState<string>("");
您可以在单个useState中处理控件数据:
import React, { useState } from "react";
const initialValues = {
fname: "",
lname: "",
country: "",
phone: "",
email: "",
username: "",
password: "",
cpassword: ""
};
export default function Form() {
const [values, setValues] = useState(initialValues);
const handleInputChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
};
return (
<form>
<input
value={values.fname}
onChange={handleInputChange}
name="fname"
label="fname"
/>
<input
value={values.lname}
onChange={handleInputChange}
name="lname"
label="lname"
/>
// ... Rest of the input fields
<button type="submit"> Submit </button>
</form>
);
}
您可以使用对象并提供接口,而不是为状态字段使用单个值
interface FormState = {
lname: string;
country: string;
phone: string;
email: string;
username: string;
password: string;
cpassword: string;
};
const [values, setValues] = useState<FormState>({
lname: "",
country: "",
phone: "",
email: "",
username: "",
password: "",
cpassword: "",
});
const handleInputChange = (field) => (e) => {
const val = e.detail.value;
setValues(values => ({
...values,
[field]: val,
}));
};
<IonItem>
<IonLabel position={"stacked"}>First Name</IonLabel>
<IonInput type={"text"} value={fname} placeholder="Enter Your First Name" onIonChange={handleInputChange('fname')}/>
</IonItem>
接口FormState={
lname:字符串;
国家:字符串;
电话:字符串;
电子邮件:字符串;
用户名:字符串;
密码:字符串;
cpassword:字符串;
};
const[values,setValues]=useState({
名称:“,
国家:“,
电话:“,
电邮:“,
用户名:“”,
密码:“”,
注册会计师密码:“,
});
常量handleInputChange=(字段)=>(e)=>{
const val=e.detail.value;
设置值(值=>({
价值观
[字段]:val,
}));
};
名字
从“React”导入React,{useState};
常数形式=()=>{
常量[inputValues,setInputValues]=useState()
const handleFormSubmit=async(e:React.MouseEvent)=>{
e、 预防默认值()
常数数据={
名称:inputValues?.name,
电子邮件:输入值?。电子邮件,
电话:输入值?电话,
收入:输入值?.name
}
常量请求选项={
方法:“POST”,
标题:{'Content-Type':'application/json'},
正文:JSON.stringify(数据)
};
试一试{
const response=等待获取('https://xyz/form-submit,请求选项)
const res=wait response.json()
console.log(res)
}捕获(错误){
console.log(错误)
}
}
常量handleInputChange=(e:React.FormEvent)=>{
常量{name,value}=e.currentTarget
setInputValues(prevState=>({…prevState,[名称]:值}))
}
返回(
React演示表
提交
);
}
导出默认表单;
示例打字脚本表单。它的特点是:
- 单个
处理程序onChange
- 一个状态对象,我们可以在其中添加任意多个键值对 没有打字脚本编译器对我们大喊大叫
- 使用ES2020可选链接
- 在DOM元素上有数据testid,以防您想运行一些单元测试
- 应根据输入字段的类型为其提供自动完成功能
- 表单提交函数示例,它使用fetch api对端点进行post调用
import React, { useState } from "react";
const initialValues = {
fname: "",
lname: "",
country: "",
phone: "",
email: "",
username: "",
password: "",
cpassword: ""
};
export default function Form() {
const [values, setValues] = useState(initialValues);
const handleInputChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
};
return (
<form>
<input
value={values.fname}
onChange={handleInputChange}
name="fname"
label="fname"
/>
<input
value={values.lname}
onChange={handleInputChange}
name="lname"
label="lname"
/>
// ... Rest of the input fields
<button type="submit"> Submit </button>
</form>
);
}
const handleRegistration = async () => {
await axios.post('http://localhost:3000/register', {
fname: values.fname,
lname: values.lname,
//Rest of the input fields
}).then(res => {
console.log(res);
onRegister();
}).catch(err => {
console.log(err);
});
}
interface FormState = {
lname: string;
country: string;
phone: string;
email: string;
username: string;
password: string;
cpassword: string;
};
const [values, setValues] = useState<FormState>({
lname: "",
country: "",
phone: "",
email: "",
username: "",
password: "",
cpassword: "",
});
const handleInputChange = (field) => (e) => {
const val = e.detail.value;
setValues(values => ({
...values,
[field]: val,
}));
};
<IonItem>
<IonLabel position={"stacked"}>First Name</IonLabel>
<IonInput type={"text"} value={fname} placeholder="Enter Your First Name" onIonChange={handleInputChange('fname')}/>
</IonItem>
import React, { useState } from 'react';
const Form = () => {
const [inputValues, setInputValues] = useState<{ [x: string]: string }>()
const handleFormSubmit = async (e: React.MouseEvent<HTMLElement>) => {
e.preventDefault()
const data = {
name: inputValues?.name,
email: inputValues?.email,
phone: inputValues?.phone,
income: inputValues?.name
}
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
};
try {
const response = await fetch('https://xyz/form-submit', requestOptions)
const res = await response.json()
console.log(res)
} catch (error) {
console.log(error)
}
}
const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
const { name, value } = e.currentTarget
setInputValues(prevState => ({ ...prevState, [name]: value }))
}
return (
<div className="Form">
<div className="form-wrapper">
<h1>Demo Form for React</h1>
<form className="form">
<input
className="form-input"
name="name"
value={inputValues?.name || ''}
onChange={handleInputChange}
placeholder="Your Name"
type="text"
data-testid="form-input-name"
/>
<input
className="form-input"
name="phone"
value={inputValues?.phone || ''}
onChange={handleInputChange}
placeholder="Your Phone"
type="tel"
data-testid="form-input-phone"
/>
<input
className="form-input"
name="email"
value={inputValues?.email || ''}
onChange={handleInputChange}
placeholder="Your Email"
type="email"
data-testid="form-input-email"
/>
<input
className="form-input"
name="income"
value={inputValues?.income || ''}
onChange={handleInputChange}
placeholder="Your Annual Income"
type="number"
data-testid="form-input-income"
/>
<button
className='form-submit'
data-testid="form-submit"
onClick={handleFormSubmit}
>
Submit
</button>
</form>
</div>
</div>
);
}
export default Form;