从react类组件中保存formData有多种方法,以下是其中几种常见的方法:
import React, { Component } from 'react';
class MyForm extends Component {
constructor(props) {
super(props);
this.state = {
formData: {
name: '',
email: '',
// 其他表单字段
}
};
}
handleChange = (event) => {
const { name, value } = event.target;
this.setState(prevState => ({
formData: {
...prevState.formData,
[name]: value
}
}));
}
handleSubmit = (event) => {
event.preventDefault();
// 可以通过访问this.state.formData来获取表单数据
console.log(this.state.formData);
}
render() {
const { formData } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<input type="text" name="name" value={formData.name} onChange={this.handleChange} />
<input type="email" name="email" value={formData.email} onChange={this.handleChange} />
{/* 其他表单字段 */}
<button type="submit">提交</button>
</form>
);
}
}
export default MyForm;
import React, { Component } from 'react';
class MyForm extends Component {
constructor(props) {
super(props);
this.formDataRef = React.createRef();
}
handleSubmit = (event) => {
event.preventDefault();
// 可以通过访问this.formDataRef.current.value来获取表单数据
console.log(this.formDataRef.current.value);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" ref={this.formDataRef} />
{/* 其他表单字段 */}
<button type="submit">提交</button>
</form>
);
}
}
export default MyForm;
以上是几种常见的从react类组件中保存formData的方法,具体选择哪种方法取决于项目需求和个人偏好。
领取专属 10元无门槛券
手把手带您无忧上云