reactjs - 如何在 React 中制作动态表单
问题描述
我正在学习反应。我的目标是制作这个对象:
"Phones": [
{
"Type": "Mobile",
"Phone_Number": "6546543"
},
{
"Type": "Home",
"Phone_Number": "6546543"
}
]
我做了一些研究,并关注了这个 YouTube 视频ReactJS - 动态添加多个输入字段。
我将从表单中获取这些值。用户可以继续添加任意数量的数字。我的代码是:
render() {
return (
<div>
<h1>The Form</h1>
<label>Contact</label>
{this.state.phones.map((phone, index) => {
return (
<div key={index}>
<input onChange={(e) => this.handleChange(e)} value={phone} />
<select>
{this.phoneTypes.map((phoneType, index) => {
return (
<option key={index} value={phoneType}>
{phoneType}
</option>
);
})}
</select>
<button onClick={(e) => this.handleRemove(e)}>Remove </button>
</div>
);
})}
<hr />
<button onClick={(e) => this.addContact(e)}>Add contact</button>
<hr />
<button onClick={(e) => this.handleSubmit(e)}>Submit</button>
</div>
);
}
我没有在这里粘贴整个代码,因为我已经创建了一个stackblitz。我的代码没有按预期工作。请投入。
解决方案
您需要在handleChange函数中为输入字段传递索引。我猜你错过了视频中的那部分。这将使输入字段可编辑。
<input
onChange={(e) => this.handleChange(e, index)}
value={phone}
/>
对于获得预期对象数组的第二部分,我更新了一些代码,请检查:
import React, { Component } from 'react';
class Questionnaire extends Component {
state = {
phones: [{ type: '', number: '' }],
};
phoneTypes = ['Mobile', 'Home', 'Office'];
addContact() {
this.setState({ phones: [...this.state.phones, { type: '', number: '' }] });
}
handleChange(e, index) {
this.state.phones[index]['number'] = e.target.value;
this.setState({ phones: this.state.phones });
}
handleRemove(index) {
this.state.phones.splice(index, 1);
console.log(this.state.phones, '$$$');
this.setState({ phones: this.state.phones });
}
handleSubmit(e) {
console.log(this.state, '$$$');
}
render() {
return (
<div>
<h1>The Form</h1>
<label>Contact</label>
{this.state.phones.map((phone, index) => {
return (
<div key={index}>
<input
onChange={(e) => this.handleChange(e, index)}
value={phone.number}
name="number"
/>
<select>
{this.phoneTypes.map((phoneType, index) => {
return (
<option key={index} value={phoneType} name="type">
{phoneType}
</option>
);
})}
</select>
<button onClick={(e) => this.handleRemove(e)}>Remove </button>
</div>
);
})}
<hr />
<button onClick={(e) => this.addContact(e)}>Add contact</button>
<hr />
<button onClick={(e) => this.handleSubmit(e)}>Submit</button>
</div>
);
}
}
export default Questionnaire;
推荐阅读
- backbone.js - 使用 Backbone.js 从 Parse Server 获取数据的问题
- java - 访问在 ReaderInterceptor/ContainerRequestFilter 中形成的元信息以在 WriterInterceptor 中使用
- python - 使用线程任务时写入同一个 SQL 表:性能问题
- python - 如何使用 pyEX 获取多个时期的收益数据?
- javascript - select之间的交互
- javascript - 如何从 Chrome 扩展程序向我的本地 python 代码发送消息
- r - 使用 call() 赋值
- migration - 我可以同时迁移和升级 NextCloud 吗?
- powershell - 解析输出/如何使用 powershell 解析输出
- python - Tableau Public 的 Python Selenium 网页抓取:如何将收藏夹分配给工作簿?